如何使用jQuery将check复选框的值添加到textarea?

时间:2009-04-25 02:35:52

标签: javascript jquery html checkbox text

如何在未检查textarea时使用jQuery删除input_oneone_1 one_3 one_4的文本,并在检查时将其添加到{{1}再次?

代码如下:

textarea

例如,textarea值应为<div id="input_one"> <input type="checkbox" value="one"> <input type="checkbox" value="one_1"> <input type="checkbox" value="one_2"> <input type="checkbox" value="one_3"> <input type="checkbox" value="one_4"> </div> <div id="input_two"> <input type="checkbox" value="two_1"> <input type="checkbox" value="two_2"> <input type="checkbox" value="two_3"> <input type="checkbox" value="two_4"> <input type="checkbox" value="two_5"> </div> <textarea id="get_checked"></textarea>

2 个答案:

答案 0 :(得分:1)

您可以使用:checked选择器选中checked复选框,然后使用.map()将复选框数组替换为其值。

$("#input_one :checkbox, #input_two :checkbox").change(function() {   
    var text = $("#input_one :checked, #input_two :checked").map(function() {
        return this.value;
    }).get().join(" ");
    $("#get_checked").val(text);
});

$(":checkbox").change(function() {   
    var text = $(":checked").map(function() {
        return this.value;
    }).get().join(" ");
    $("#get_checked").val(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input_one">
    <input type="checkbox" value="one" />
    <input type="checkbox" value="one_1" />
    <input type="checkbox" value="one_2" />
    <input type="checkbox" value="one_3" />
    <input type="checkbox" value="one_4" />
</div>
<div id="input_two">
    <input type="checkbox" value="two_1" />
    <input type="checkbox" value="two_2" />
    <input type="checkbox" value="two_3" />
    <input type="checkbox" value="two_4" />
    <input type="checkbox" value="two_5" />
</div>
<textarea id="get_checked"></textarea>

正如你在question中所说,resutl文本被空格分割。

答案 1 :(得分:0)

希望这有帮助

function updateTextArea() {
    var allVals = [];
    $('#input_one :checked,#input_two :checked').each(function () {
        allVals.push($(this).val());
    });
    $('#get_checked').val(allVals);
}
$(function () {
    $('#input_one input,#input_two input').click(updateTextArea);
});

jsfiddle

相关问题