user3271762
user3271762

Reputation: 23

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?

Upvotes: 0

Views: 974

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388436

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)

Upvotes: 1

Youssef Lahssini
Youssef Lahssini

Reputation: 131

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/

Upvotes: 0

Ramacciotti
Ramacciotti

Reputation: 106

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.

Upvotes: 0

Related Questions