开发者

Check if all radio buttons checked having particular value

<input type="radio" checked="checked" value="true" name="child">
<span class="label">Show</span>
<input type="radio" class="hide" value="false" name="child">
<span class="label">Hide</span>

and another radio button on the same page

<input type="radio" checked="checked" value="true" name="baby">
<span class="label">Show</span>
<input type="radio" class="hide" value="false" name="baby">
<span class="label">Hide</span>
开发者_运维百科

I need to know if all the radio buttons having value="false" are checked using javascript.

Note: The radio button names are different


If you use jQuery, it's very clean:

if ($("input[type='radio'][value='false']").not(':selected').length==0) {
  // Do what you want
}

The jQuery expression means all the false radio buttons are selected


boudou beat me by 35 seconds...

However, besides the for you can use a foreach logic:

var buttons = document.getElementsByTagName("input");

for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    var id = button.getAttribute("id");
    var type = button.getAttribute("type");
    var value = button.getAttribute("value");
    var checked = button.getAttribute("checked");
    if (type === "radio" && value === "false" && checked === "checked") {
        alert(id);
    }
}

The script can be condensed, it's written like this to allow a better understanding.

See a demo here.


You can try this:

function testRadios() {
    var r = document.getElementsByTagName("input");

    for (var i=0; i < r.length; i++) {
        if (   (r[i].type == "radio")
            && (r[i].value == "false")
            && (r[i].checked != "checked")) {
            return false;
    }
    return true;
}

PS: Use <label> instead of <span class="label">.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜