jquery - 在表单提交时获取数组中选中的复选框值

标签 jquery html

我想获取复选框的所有值并提醒它们在表单提交时被选中,

到目前为止,这是我尝试过的:

HTML

<form id="calform">
<input type="checkbox" value="one_name" />
<input type="checkbox" value="one_name1"/>
<input type="checkbox" value="one_name2"/>
<input type="submit" value="Submit" />
</form>

jQuery 脚本

      $("#calform").submit(function(e){

    // array that will store all the values for checked ones
    var allVals = [];

    $('input[type="checkbox"] :checked').each(function() {

    // looping through each checkbox and storing values in array for checked ones.
    allVals.push($(this).val());

    });

    alert(allVals);

    e.preventDefault();
    });

这里是JSFIDDLE

表单提交时警告框显示为空。

最佳答案

使用 $('input[type="checkbox"]:checked'),注意 input[type="checkbox"] 和伪类:checked:

UPDATED EXAMPLE HERE

 $("#calform").submit(function (e) {

     var allVals = [];

     $('input[type="checkbox"]:checked').each(function () {
      //     removed the space ^

         allVals.push($(this).val());
     });
     alert(allVals);

     e.preventDefault();
 });

关于jquery - 在表单提交时获取数组中选中的复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21397953/

相关文章:

jquery - 项目一项一项地淡出/淡出?

javascript - 具有事件类的平滑滚动导航

jquery - 可点击的下拉菜单

html - 设置 -webkit-overflow-scrolling : touch 时,z-index 在 iOS 上的处理方式不同

html - 如何将移动设备上的所有共享按钮集中到一行?

jQuery Mobile 主题 - 在哪里获取它们?重新调整 jQTouch 主题的用途?

单击时的 jquery 列值

javascript - fancybox 使鼠标滚轮淡入图片水平

javascript - 变量没有变化。错误在哪里?

php - 动态显示带有相应标题的表格