jQuery追加和删除复选框中的值到textarea [英] jQuery append and remove values from checkbox to textarea

查看:249
本文介绍了jQuery追加和删除复选框中的值到textarea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将复选框的值附加或删除到textarea,我尝试使用以下代码对textbox可以正常工作,但不能在textarea上正常工作.此外,它仅添加有关单击功能而不是检查功能的信息.任何人都可以通过代码帮助我,以便在选中时将选项值添加到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:

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

推荐答案

您可以做更多类似的事情

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

这篇关于jQuery追加和删除复选框中的值到textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆