Toggle text, on a checkbox input change
I searched and tried a lot of codes & samples but I didn't get to my
point. 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? Tank you so much. P.S: I also want to separate texts from
each other by a comma.
No comments:
Post a Comment