How can I set a Boolean value in jQuery based on an input of type radio?

1.3k Views Asked by At

I have a pair of inputs of type radio like so:

<label>YES</label>
<input type="radio" name="uscitizen" id="uscitizenyes" value="YES" required />
<label>NO</label>
<input type="radio" name="uscitizen" id="uscitizenno" value="NO" />

To set the value of a Sharepoint 2010 List item ('ptli_USCitizen' in this case), is this the best way to accomplish it:

oListItem.set_item('ptli_USCitizen', ($('uscitizenyes').val() == 'YES'));

...or is there a more "accepted patternful" way?

3

There are 3 best solutions below

1
Gregg Duncan On BEST ANSWER

This will work.

oListItem.set_item('ptli_USCitizen', ($('[name="uscitizen"]:checked').val() == 'YES'));

But the best way to handle a boolean value in the User Interface is a Checkbox rather than radio buttons.

Us Citizen: <input type='checkbox' id='uscitizen' name='uscitizen' />

Then use:

oListItem.set_item('ptli_USCitizen', ($('#uscitizen').is(':checked'));
2
M156 On

Try this to get a bool result without the explicit need for checking for YES.

$('#radio_button').is(':checked')
3
charlietfl On

Can use the :checked selector

$('[name=uscitizenyes]:checked').val()

Assumes you want the value for your list as opposed to boolean shown in question

oListItem.set_item('ptli_USCitizen',$('[name=uscitizenyes]:checked').val())

For boolean can use the ID for YES and is(':checked')

oListItem.set_item('ptli_USCitizen',$('#uscitizenyes').is(':checked'))