简体   繁体   中英

How to get the value of selected radio button

My HTML part is below:

<input id="yes" save-value="yes" value="no" name="view_y" class="switch-input yes" type="radio">
<label checked="checked" class="switch-label switch-label-off selected" for="yes">Yes</label>
<input id="no" save-value="no" value="no" name="view_n" class="switch-input no" type="radio">
<label class="switch-label switch-label-on" for="no">No</label>
<span class="switch-selection"></span>

When I click each button checked="checked" and selected options will be changing from yes to no labels.

With these options, how can I get the save-value of selected radio button. Since, am using Handlebars js (json) on my value option I want to get the save-value of selected radio button.

How an I do that?

Assuming the class switch-input is assigned to only these two input elements, you can use it along with the checked selector

var value = $('input.switch-input').filter(':checked').attr('save-value');
//or var value = $('input.switch-input:checked').attr('save-value');

Note: Prefer to use data-* attributes to store custom attributes


I think the radio buttons are not actually getting checked, only the labels attributes are changed so, add a additional class to the labels like myclass

<input id="yes" save-value="yes" value="no" name="view_y" class="switch-input yes" type="radio"/>
<label checked="checked" class="myclass switch-label switch-label-off selected" for="yes">Yes</label>
<input id="no" save-value="no" value="no" name="view_n" class="switch-input no" type="radio"/>
<label class="myclass switch-label switch-label-on" for="no">No</label>
<span class="switch-selection"></span>

then

var value = $('.myclass[checked="checked"]').prev('input').attr('save-value');
console.log(value)

First, your radio buttons should have the same name attribute, say view , so that the browser will restrict selection to only one of them. Then, you can use $('[name="view"]:checked').val() to capture the value of the radio button that is selected.

You have some errors in your HTML code, you put the checked attribute on the wrong tag, look in this example:

$('body').on('change','input',function() {
   $('.switch-selection').html($(this).attr('save-value'));
});

http://jsfiddle.net/9Pj3g/2/

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