Question

i have following HTML struture, I am unable to get the value of a radio button when i select my selector as explained in my Jquery Code Below.

<div class="option-radio-box">
<input id="pixel" class="css-checkbox" type="radio" value="pixel" name="type">
<label class="css-label" for="radio1">
<img width="25" height="20" alt="" src="images/opt-ico1.png">
Pixel by
<span>Pixel</span>
</label>
</div>
<div class="option-radio-box">
<input id="pair" class="css-checkbox" type="radio" checked="checked" value="pair" name="type">
<label class="css-label" for="radio2">
<img width="25" height="20" alt="" src="images/opt-ico2.png">
Duplicate
<span>Search</span>
</label>
</div>

And following Jquery code,

  $('.css-label').on('click', function() {
  alert(jQuery(this).closest('input:radio[name=type]').id);});
Was it helpful?

Solution

The radio button is not a parent, but a sibling, and a jQuery object has no .id property

$('.css-label').on('click', function() {
      alert( $(this).siblings('input:radio[name=type]').prop('id') );
});

FIDDLE

OTHER TIPS

closest() searches the element's ancestors, whereas the input element is a sibling in your HTML. You can do something like this:

$('.css-label').on('click', function() {
  alert($(this).siblings('input[name="type"]:checked').val());
});

Try this JSFIDDLE

$('.css-label').on('click', function() {
    parentElement = jQuery(this).parents('.option-radio-box');
alert($("input[type='radio']",parentElement).attr("id"));  
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top