jquerycheckboxtoggle

Toggle text, on a checkbox input change


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.


Solution

  • You need to amend the logic so that the text is generated taking into account all the checkboxes which are checked, not the one which was clicked on. Try this:

    var setCountryText = function() {
        var $p = $('.countries > p').empty();
        $('.chbxs :checkbox:checked').each(function() {
            $p.append('<span>' + $(this).next('label').text() + '</span>');
        });
    }
    
    $('.chbxs input[type="checkbox"]').click(setCountryText);
    

    Example fiddle