Karthik Malla
Karthik Malla

Reputation: 5820

jQuery append and remove values from checkbox to textarea

I am trying to append or remove values of checkbox to textarea, I tried using the following code which is working fine with textbox but not textarea. Also, it just adds information on click function not on check function. Can anyone please help me with code to add the option value to textarea (not textbox) on check and should be removed on uncheck.

<input id="fulloptions" type="text" value="" />

<div id="alloptions">
    <ul>
    <li><input type="checkbox" name="option1" value="Option1" /> Test1</li>
    <li><input type="checkbox" name="option1" value="Option2" /> Test2</li>
    <li><input type="checkbox" name="option1" value="Option3" /> Test3</li>
    </ul>
</div> 

Javascript :

$("#alloptions li input[type='checkbox']").click(function(e){    
    var cmd = $(this).val();    
        command = $("#fulloptions").val();
    if (command.indexOf(' '+cmd+' ')==0)
        return;
    else {
        $('#fulloptions').attr('value', cmd);
    }
});

I tried the following code which didn't work for me

$('input[type=checkbox]').change(function () {
    if ($(this).is(':checked')) {
        var text = $(this).val() + " ";
        insertAtCursor(textarea, text);    
    }
});

Upvotes: 2

Views: 2178

Answers (1)

adeneo
adeneo

Reputation: 318372

You could do something more like this

var checkboxes = $("#alloptions li input[type='checkbox']");

checkboxes.on('change', function() {
    $('#fulloptions').val(
        checkboxes.filter(':checked').map(function(item) {
            return this.value;
        }).get().join(', ')
     );
});

FIDDLE

Upvotes: 7

Related Questions