Jquery遍历checkbox获取选中项value值的方法

  源码:

  

复制代码 代码如下:

  jQuery(function($){

  $("input[name='key']:checkbox").click(function(){

  var ids = '';

  var flag = 0;

  $("#ids").attr("value",ids);

  $("input[name='key']:checkbox").each(function(){

  if (true == $(this).attr("checked")) {

  ids += $(this).attr('value')+',';

  flag += 1;

  }

  });

  if(0 < flag) {

  $("#ids").attr("value",ids);

  return true;

  }else {

  alert('请至少选择一项!');

  return false;

  }

  });

  });

  本源码的功能:

  获取name=‘key'的复选框的值,将选中项的 value 写到隐藏域 <input type="hidden" name="ids" id="ids" value="" /> 的表单中。

  核心语句:

  

复制代码 代码如下:

  $("input[name='key']:checkbox").each(function(){

  if (true == $(this).attr("checked")) {

  ids += $(this).attr('value')+',';

  }

  });

  在HTML中,如果一个复选框被选中,对应的标记为 checked="checked"。 但如果用jquery alert($("#id").attr("checked")) 则会提示您是"true"而不是"checked",所以判断 if("checked"==$("#id").attr("checked")) 是错误的,应该如上面那样书写: if(true == $("#id").attr("checked"))