简体   繁体   中英

jQuery - Populate closest hidden input with radio's value

I have the following HTML and jQuery to populate hidden fields within each <td> element:

<td>
    <div id="sex_div" style="text-align: left; width:120;">
        <input type="hidden" id="sex" value=""/>
        <input type="radio" id="sex_male" name="sex_div" value="M"/><label for="sex_male">Male</label>
        <input type="radio" id="sex_female" name="sex_div" value="F"/><label for="sex_female">Female</label>
    </div>
</td>

The jQuery I have is as follows:

$("input :radio").click(function() {
    $(this).siblings("input [type='hidden']").val($(this).val());
});

and obviously the buttonset,

$("#sex_div").buttonset();

This is just a small part of the whole form. The rest all looks similar. Now the issue is that the hidden field is not being set when clicking/selecting a radio button. I have been struggling with this seemingly easy problem for two days now!

Thanks for any help!

$(this).siblings("input[type='hidden']").val($(this).val());

There should be no space between input and [type='hidden'] . Spaces in selectors mean to search for descendant elements that match the next token.

you need to remove space in your selector

$("input:radio").click(function() {
    $(this).siblings("input[type='hidden']").val($(this).val());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM