Reputation: 988
<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>
How to store it into array and display all the check-box checked value into the "#display" div immediately when someone is checked the check-box and also remove the value when someone is unchecked the check-box. For example, When I click on Banana then the "#display" div will display Banana and I continue to click on Grape then it will display Banana, Grape. Remove the word "Banana" from the "#display" div when unchecked the check-box so the "#display" div will only display "Grape". In Jquery.
Any help will be very much appreciated.
Upvotes: 0
Views: 5398
Reputation: 36531
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);
})
Upvotes: 3
Reputation: 1889
$(".myBox").on("change", "[type=checkbox]", function () {
var s = "";
$(".myBox [type=checkbox]:checked").each(function () {
s += (s == '') ? this.value : "," + this.value;
});
$("#display").html(s);
});
Upvotes: 0
Reputation: 11371
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/
Upvotes: 0