如何在选中所有输入复选框和单选组后显示javascript确认消息

how show javascript confirm message after all input checkbox and radio groups checked?

本文关键字:单选组 显示 javascript 消息 确认 复选框 输入      更新时间:2023-09-26

点击提交按钮后需要显示一条确认消息,但是,只有在选中我的单选框和复选框后才需要显示此窗口消息,怎么做?

http://jsfiddle.net/G3LTe/

HTML:

<form method="post" action="">
    <label>
        <input type="radio" name="group[1]" value="1">1
    </label>
    <label>
        <input type="radio" name="group[1]" value="2">2
    </label>
    <label>
        <input type="radio" name="group[1]" value="3">3
    </label>
        <br>
   <!-- 2 -->
     <label>
        <input type="radio" name="group[2]" value="1">1
    </label>
    <label>
        <input type="radio" name="group[2]" value="2">2
    </label>
    <label>
        <input type="radio" name="group[2]" value="3">3
    </label>
        <br>
 <input type="submit" value="send">
</form>

JS-

$('form').submit(function(){
    var confirmacao = confirm("WARNING:'n go to next step? or cancel?");
    if(confirmacao == true) {
        console.log("OK");
        return true;
    } else {
        console.log("O envio foi cancelado");
        return false;
    }
});

您可以检查特定的单选按钮组是否至少选择了一个单选按钮,如下所示:

if ($(':radio[name="nameOfGroup"]:checked').length > 0)
{
    // at least one radio button with the name nameOfGroup is checked
}

因此,浏览每个组,检查该组是否至少选择了一个单选按钮,如果选择了,则进入确认对话框:

var groups = {};
// get all of the unique radio button groups
$(':radio', form).each(function() {
    // object names are unique
    groups[this.name] = true;
});
var proceed = true;
$.each(groups, function(group, dummy) {
    if ($(':radio[name="' + group + '"]:checked').length == 0)
    {
        // none of the radio buttons of this group are checked, abort
        proceed = false;
        // break out of the .each() loop
        return false;
    }
});
if (!proceed)
{
    alert('Please check at least 1 radio button from each group!');
    return false;
}

看看这把小提琴:http://jsfiddle.net/b2SL7/

(我的代码示例可能会有所简化,但为了清楚地说明发生了什么,我这样写了出来。)

(针对任意组进行编辑以解决OP的问题)