简体   繁体   中英

Get value of a checked radio button

How can I get a value of a checked radio button of a group of related radio buttons without using their ids? I can try something like this, but it is not generic enough.

var boxes = $('input[name=BankAccountTypeGroup]:checked');
$(boxes).each(function () {
   if ($(this).val() == 'Savings') {
       //
   }
})

Radio buttons are grouped by the name attribute, so your current selector should work fine (without even looping) -- if you have multiple groups of common named groups, you can use the ^= (starts with) inside attribute selector to get all the groups.

Example, you have multiple radio groups starting with "BankAccount"

var groups = $(":radio[name^=BankAccount]:checked").map(function() {
    return this.value;
}).get();

.map() returns a nice array of all your checked values for radio groups starting with "BankAccount"

var boxes = $('input[name=BankAccountTypeGroup]:checked');
if (boxes.length==1) //test it, maybe there is no radio checked
    {
        alert(boxes[0].value); //boxes[0] is the first and only-checked element, 
    }

Try this....

var $boxes = $('#yourcontaineridOfAllCheckboxes').find('input[type=radio]:checked'));
    $($boxes).each(function () {
       if ($(this).val() == 'Savings') {
           //
       }
    })

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