javascript - Filter Radio Elements -
i have jquery variable of array of radio elements. want further select specific element based on value.
below idea of have i'm still not sure how 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>
the .find()
method attempt select descendant elements. since input
element self-closed , doesn't contain descendant elements, nothing selected.
it seems want .filter()
method instead:
var gender = 1; var radiobuttons = $("[name='gender']"); radiobuttons.filter(function () { return this.value === gender.tostring(); }).prop('checked', true);
or using .is()
method:
radiobuttons.filter(function () { return $(this).is("[value='" + gender + "']"); }).prop('checked', true);
however, simpler use 2 attribute selectors when selecting elements instead:
var gender = 1; $("[name='gender'][value='" + gender + "']").prop('checked', true);
Comments
Post a Comment