Jquery 从复选框中获取多个选中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14679916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:50:55  来源:igfitidea点击:

Jquery get multiple checked values from checkbox

jquerycheckbox

提问by conmen

My form have following checkbox and I want to tick the option to show an alert with checked values, but there is nothing happen to show up the alert when I ticked it:

我的表单有以下复选框,我想勾选显示带有选中值的警报的选项,但是当我勾选它时没有显示警报:

<form id="booking_form">
    <input type="checkbox" name="bType[]" id="bType" value="A,200">&nbsp;Type A - USD200<br>
    <input type="checkbox" name="bType[]" id="bType" value="B,150">&nbsp;Type B - USD150<br>
    <input type="checkbox" name="bType[]" id="bType" value="C,100">&nbsp;Type C - USD100<br>
    <input type="checkbox" name="bType[]" id="bType" value="D,50">&nbsp;Type D - USD50<br>

</form>

and I have JQ script:

我有 JQ 脚本:

<script>
$("input[type=checkbox]:checked").each ( function() {
    alert ( $(this).val() );
});
</script>

please advise, thanks.

请指教,谢谢。

回答by belens

You have to add an event handler that initiates the code. Now it runs when the page is loading.

您必须添加一个启动代码的事件处理程序。现在它在页面加载时运行。

For instance, you can let a button click handle it:

例如,您可以让按钮单击来处理它:

$('.btn').click(function(){
    $("input[type=checkbox]:checked").each(function() {
        alert( $(this).val() );
    });
});

Here's an example: http://jsfiddle.net/tMRvL/

这是一个例子:http: //jsfiddle.net/tMRvL/

回答by Jonathan de M.

That should works

那应该有效

  $("input[type=checkbox]").change( function() {
    if($(this).is(":checked")){
       alert( $(this).val() );
    }
  });

Demo on Jsfiddle, other demo on JSBin

演示上的jsfiddle在JSBin其他演示

回答by Tran Anh Hien

<script>
    $("[type=checkbox]:checked").each ( function() {
        console.log($(this).val());
    });
</script>

Worked for me :)

为我工作:)