jquery怎样获取多个复选框的值?

jquery的遍历方法可以获取复选框所欲的选中值

1
2
$( "input:checkbox:checked" ).each( function (index,element));    // 为所有选中的复选框执行函数,函数体中可以取出每个复选框的值
$( "input:checkbox:checked" ).map( function (index,domElement));  // 将所有选中的复选框通过函数返回值生成新的jQuery 对象

实例演示:点击按钮获取checkbox的选中值

  1. 创建Html元素

    1
    2
    3
    4
    5
    6
    7
    8
    < div  class = "box" >
         < span >点击按钮获取checkbox的选中值:</ span >
         < div  class = "content" >
            < input  type = 'checkbox'  name = 'message'  value = '1' />发送短信
            < input  type = 'checkbox'  name = 'message'  value = '2' />发送邮件
         </ div >
         < input  type = "button"  value = "提交" >
    </ div >
  2. 设置css样式

    1
    2
    3
    div.box{ width : 300px ; padding : 20px ; margin : 20px ; border : 4px  dashed  #ccc ;}
    div.box>span{ color : #999 ; font-style : italic ;}
    div.content{ width : 250px ; margin : 10px  0 ; padding : 20px ; border : 2px  solid  #ff6666 ;}
  3. 编写jquery代码

    1
    2
    3
    4
    5
    6
    7
    8
    $( function (){ 
         $( "input:button" ).click( function () {
             text = $( "input:checkbox[name='message']:checked" ).map( function (index,elem) {
                 return  $(elem).val();
             }).get().join( ',' );
             alert( "选中的checkbox的值为:" +text);
         });
    });
  4. 观察效果

猜你喜欢

转载自www.cnblogs.com/hedianzhan/p/9126235.html