Reputation: 897
I have a jquery variable of an array of radio elements. I want to further select a specific element based on a value.
Below is an idea of what I have but I'm still not sure how to accomplish this.
var gender = 1;
var radiobuttons = $('[name=\'gender\']'); //should contain 2 radio elements
radiobuttons.find('[value=\'' + gender + '\']').prop('checked', true);
html
<label>Female<input type="radio" name="gender" value="0"></label>
<label>Male<input type="radio" name="gender" value="1"></label>
Upvotes: 1
Views: 69
Reputation: 240948
The .find()
method will attempt to select descendant elements. Since an input
element is self-closed and doesn't contain any descendant elements, nothing is selected.
It seems like you want the .filter()
method instead:
var gender = 1;
var radiobuttons = $("[name='gender']");
radiobuttons.filter(function () {
return this.value === gender.toString();
}).prop('checked', true);
or using the .is()
method:
radiobuttons.filter(function () {
return $(this).is("[value='" + gender + "']");
}).prop('checked', true);
However, it would be simpler just to use two attribute selectors when initially selecting the elements instead:
var gender = 1;
$("[name='gender'][value='" + gender + "']").prop('checked', true);
Upvotes: 3