2

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);    
    }
});

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.