使用复选框中选中的值自动填充文本框值,但保留手动输入的值

Auto populate the textbox value with values checked in checkboxes but retain the values that are manually entered

本文关键字:手动输入 保留 文本 复选框 填充      更新时间:2023-09-26

我使用下面的jquery根据选中或未选中复选框的值自动填充文本框

function updateTextArea() {
        var allVals = [];
        $('#all :checked').each(function () {
                allVals.push($(this).val());
        });
        document.getElementById('txtbox').value = allVals;
    }
    $(function () {
        $('#all input').click(updateTextArea);
        updateTextArea();
    });

我的html代码是

<div id="all">
<input id="txtbox" type="text" Height="100px"  Width="770px"  />   
  <input id="Checkbox2" type="checkbox" value="abc1@abc.com" />
  <input id="Checkbox3" type="checkbox" value="abc2@abc.com" />
  <input id="Checkbox4" type="checkbox" value="abc3@abc.com" />
  <input id="Checkbox5" type="checkbox" value="abc4@abc.com" />
</div>

上面的jquery适用于复选框的每一个选中和取消选中事件,并将其值填充到用逗号分隔的文本框中。我怎样才能做到这一点?

我将使用的一般技术是:

每次选中或取消选中时:
1.用逗号将列表拆分成一个数组
2.收集所有选中的预设电子邮件值(您已经在这样做了)
3.找到每个不在预设数组中的拆分值,并将其放在一边
4.插入所有检查的预设值,然后添加所有奇数,反之亦然。

这不会保留顺序,但会保留任何手动输入的值。维持秩序是可以做到的,但会有点棘手。

您还可以考虑只使用一个单独的"附加电子邮件"文本框,这将降低复杂性,并可能使用户更直观。

代码:

function updateTextArea() {
    var allVals = [];
    var checkedVals = [];
    $('#all input[type=checkbox]').each(function () {
        allVals.push($(this).val());
    });
    $('#all :checked').each(function () {
        checkedVals.push($(this).val());
    });
    var potentialOtherEmails = $("#txtbox").val().split(",");
    var confirmedOtherEmails = [];
    $(potentialOtherEmails).each(function(index,value) {
        if ($.inArray(value, allVals) == -1) {
            confirmedOtherEmails.push(value);
        }
    });
    $("#txtbox").val($.merge(checkedVals,confirmedOtherEmails));    
}
$(function () {
    $('#all input').click(updateTextArea);
    updateTextArea();
});

好了。。。。

$(function () {
    txtbox = $("#txtbox");
    var prevVal;
    $("input[type='checkbox']").click(function() {
        prevVal = txtbox.val();
        if($(this).is(":checked"))
        {
            txtbox.val(prevVal + $(this).val() + ", ");
        }
        else
        {
            prevVal = prevVal.replace($(this).val()+", ", "");
            txtbox.val(prevVal);
        }
    });
});

在现有代码中需要注意的一点是,您对DOM的查询过多(每次进行检查时都会对复选框进行迭代),不要这样做。此外,当JQuery可用时,为什么要使用document.getElementById?:-)这个可能不是一个完美的解决方案,但有效!!