简体   繁体   中英

Get the selected value of a list of radio buttons

I have a list of radio buttons each with the same name attribute. The following JavaScript is meant to detect a change in any of the buttons and pass the selected value to the getColumnNames() method.

$("input[name=SelectedSheet]:radio").change(function () {
    getColumnNames(this.val());
})

It detects when any of the buttons change, but it doesn't pass the string value of the selected radio button.

In Firebug, when one of the radio buttons is clicked, the this keyword contains the following:

input#SelectedSheet_Second Sheet attribute value = "Second Sheet"

Btw, SelectedSheet is the name attribute of the list of radio buttons.

How do I pass the value of the selected attribute to the getColumnNames() method?

.val() is a jQuery method, so you must wrap this with $() to use it:

getColumnNames($(this).val());

Or you can just use plain JS:

getColumnNames(this.value);

You can remove the :radio, since it will find it by the name. Then use $(this).val() instead

<input type="radio" name="SelectedSheet" value="sheet1" />
<input type="radio" name="SelectedSheet" value="sheet2" />
<input type="radio" name="SelectedSheet" value="sheet3" />

$(document).ready(function () {
   $('input[name="SelectedSheet"]').change(function () {
      alert($(this).val());
   });
});

http://jsfiddle.net/fxsupvhj/

Try to use $(this).val(); inside your code.

$("input[name=SelectedSheet]:radio").change(function () {
    getColumnNames($(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