[Solved] Javascript/jQuery: search within object


HTML

<div class="days">
    <input id="dayMonday" name="days-select" type="radio" value="Mon">
    <label for="dayMonday">Monday</label>
    <br>
    <input id="dayTuesday" name="days-select" type="radio" value="Tue">
    <label for="dayTuesday">Tuesday</label>
</div>

script

  $(document).ready(function () {
      //your .days selector is actually getting the div and not the radio button
      var div = $('.days');
      //maybe here you want to do some things with the div...
      //...
      var radiobtn = div.find('input[value="Tue"]');
      //maybe here you want to do some things with the radio button...
      //...

      //now you have the correct element...
      radiobtn.prop('checked', true);

      //F12 in Chrome to see the console
      console.log(radiobtn);
      //notice the selector property returns: .days input[value="Tue"]
      console.log(radiobtn.selector);
      //so you could just do this all in one line:
      $('.days input[value="Tue"]').prop('checked', true);

      //see last commented line regarding this next line...
      //$('.days input[value="Tue"]').click(
      //     function(){ console.log("you clicked Tuesday");});
      //Note: you could do this: 
      //radiobtn.click();
      //... or this:
      //$('.days input[value="Tue"]').click();
      //but it also fires the click event which is why you would see 
      //"you clicked Tuesday" in the console with the above line uncommented
      });

Here’s a fiddle.

0

solved Javascript/jQuery: search within object