2010-08-10 175 views
1

现在我得到的价值,如果我选择复选框(ID被选中), ,但如何获得值时,我未选定(ID是未选中)?jquery,取消选择复选框

例如我推1,我得到价值1.当我取消选择1,我得到价值1. 我希望你明白我的问题。

<script> 
$(document).ready(function() 
{ 
    $("input[type=checkbox]").change(function(event){ 
     $("#result").html("&id=" + this.value); 
    }); 
}); 
</script> 
</head>                 
<body>                 
<input type="checkbox" name="checkbox_pref" value = "1"/>1 
<input type="checkbox" name="checkbox_pref" value = "2"/>2 
<input type="checkbox" name="checkbox_pref" value = "3"/>3 
<div id="result">result ...</div> 

回答

1

我简单地创建与所有的检查值的数组。

然后我可以使用join来创建字符串以备后用。

$(document).ready(function() { 
    var $inputs = $("input[type=checkbox]"); 
    $inputs.change(function(event){ 
     var list = []; 
     $inputs.filter(':checked').each(function() { 
      list.push($(this).val()); 
     }); 
     $("#result").html("&id=" + list.join(",")); // Produces: &id = 1,2,3 (If they were all checked) 
    }); 
}); 

+1

..我只是尝试这样做,也没有工作。 http://jsfiddle.net/8nhYq/。你确定这有效吗? – Hristo 2010-08-10 20:18:03

+0

谢谢,我修复了语法错误,请尝试:http://jsfiddle.net/8nhYq/1/,用有效的JS更新后 – 2010-08-10 21:10:33

0

我相信如果你使用this.attr('checked')你应该得到一个布尔值。

,或者你可以做

this.is( ':检查')