I have 3 checkbox inputs and 3 labels after each, and a div including a <p> tag.
I want when I check each checkbox, the next label text to be copied in the <p> tag, and when I uncheck it, remove the text in <p> tag. I mean toggling the label text inside the <p> tag by changing the inputs.
my HTML code :
<div class="chbxs">
<input type="checkbox" name="country" id="Iran" rel="Iran" />
<label for="Iran">Mashad,Tehran</label>
<input type="checkbox" name="country" id="England" rel="England" />
<label for="England">London,Manchester</label>
<input type="checkbox" name="country" id="USA" rel="USA" />
<label for="USA">California,NewYork</label>
</div>
<div class="countries">
<p></p>
</div>
my jquery code :
$('.chbxs input[type="checkbox"]').click(function() {
var chkdChkbox = $(this).next('label').text();
if ($(this).prop('checked') == true) {
$('.countries > p').append('<span>' + chkdChkbox + '</span>');
}
else {
$('.countries > p').children('span').remove();
}
});
The problem is that if I uncheck an input, all spans will be removed. How can I fix this?
P.S: I also want to separate texts from each other by a comma.
idorclassto the span.idwould be better if there would be only one.