简体   繁体   中英

Getting value of multiple radio buttons groups javascript

I am currently working on a form which has to process a data filled in a by a client. It has a few radio groups and I'd like to get the value of it when it's changed.

<input type="radio" name="domain" value="no">
<input type="radio" name="domain" value="yes">

<input type="radio" name="hosting" value="no">
<input type="radio" name="hosting" value="yes">

I found a function like it somewhere, but it does not work the way I want.

    function getSelectedValueFor(name) {
        alert(document.getElementsByTagName(name).length);
        for (var i = 0; i <
            document.getElementsByTagName(name).length; i++) {
            var input = document.getElementsByTagName(name)[i];
                if (input.type == "radio" && input.checked) {
                    return input.value;
                }
        }
        return null;
}

It basically should work like this, and work for "getSelectedValueFor()" should be reusable:

$('input[name="hosting"]').change(function(){
    var x = getSelectedValueFor("hosting");
    console.log(x + " test");
    if(x == "yes") { $('#hosting').slideDown(); }
    else if(x == "yes") { $('#hosting').slideUp(); }
    return;
});

Is there anyone who can help me out? All help is appreciated.

您可以使用此行简单地获取所选值

var x = $('input[name="hosting"]:checked').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