0
<div class="myBox">
    <input type = "checkbox" id = "Banana" value = "Banana" />
    <input type = "checkbox" id = "Orange" value = "Orange" />
    <input type = "checkbox" id = "Apple" value = "Apple" />
    <input type = "checkbox" id = "Papaya" value = "Papaya" />
    <input type = "checkbox" id = "Watermelon" value = "Watermelon" />
    <input type = "checkbox" id = "Grape" value = "Grape" />
</div>

<div id="display">
</div>

それを配列に保存し、誰かがチェックボックスをオンにしたときにすぐにすべてのチェックボックスのチェックされた値を「#display」divに表示し、誰かがチェックボックスをオフにしたときに値を削除する方法。たとえば、Banana をクリックすると、「#display」div に Banana が表示され、続けて Grape をクリックすると、Banana, Grape が表示されます。チェックボックスをオフにすると、「#display」div から「Banana」という単語を削除して、「#display」div に「Grape」のみが表示されるようにします。Jクエリで。

どんな助けでも大歓迎です。

4

3 に答える 3

3

using map() function to get the checked values... and join() to join the array with ,.

try this

$('.myBox  input:checkbox').change(function(){
  var tempValue='';
  tempValue=$('.myBox  input:checkbox').map(function(n){
      if(this.checked){
            return  this.value;
          };
   }).get().join(',');

   $('#display').html(tempValue);
})

OR

simple way

 $('.myBox  input:checkbox').change(function(){
  var tempValue='';
tempValue=$('.myBox  input:checkbox:checked').map(function(n){  //map all the checked value to tempValue with `,` seperated
            return  this.value;
   }).get().join(',');

   $('#display').html(tempValue);
})

fiddle here

于 2013-07-27T18:53:08.107 に答える
0
$(".myBox").on("change", "[type=checkbox]", function () {
    var s = "";
    $(".myBox [type=checkbox]:checked").each(function () {
        s += (s == '') ? this.value : "," + this.value;
    });
    $("#display").html(s);
});
于 2013-07-27T18:58:33.577 に答える
0

You will need something like this :

$(".myBox").on("change", "[type=checkbox]", function () {
    var s = "";
    $(".myBox [type=checkbox]:checked").each(function () {
        s += this.value + ",";
    });
    $("#display").html(s.slice(0, s.length -1));
});

Everytime a change happens in the text box, each event gets the values of checked checkboxes and adds them to the div.

Demo : http://jsfiddle.net/hungerpain/cqZcX/

于 2013-07-27T18:54:18.813 に答える