【问题标题】:jQuery to populate array-named form fields based on first entered value where number of fields is unknownjQuery 根据字段数未知的第一个输入值填充数组命名的表单字段
【发布时间】:2011-02-07 06:03:50
【问题描述】:

您好,

我有一个输入数量可变的表单,其简化版本如下所示:

<form>
<label for="same">all the same as first?</label>
<input id="same" name="same" type="checkbox" />
<input type="text" id="foo[1]" name="foo[1]" value="" />
<input type="text" id="foo[2]" name="foo[2]" value="" />
<input type="text" id="foo[3]" name="foo[3]" value="" />
<input type="text" id="foo[4]" name="foo[4]" value="" />
<input type="text" id="foo[5]" name="foo[5]" value="" />
</form>

这个想法是勾选#same 复选框并让jQuery 将#foo[1] 中的值复制到#foo[2]、#foo[3] 等。如果未选中#same,它们还需要清除。

根据表单前一阶段的输入,可以有任意数量的#foo 输入,这给我带来了麻烦。我确定我遗漏了一些明显的东西,但我无法让 $('#dest').val($('#source').val()); 的任何变化起作用。

救命!

【问题讨论】:

    标签: jquery forms field populate


    【解决方案1】:
        $("input#same").click(function(){
          var checkBox = $(this);
           if (checkBox.attr("checked")){
             $("form input[name^=foo]").val($("input[name^=foo]:first").val());
            }else{
              $("form input[name^=foo]:not(:first)").val("");
            }
        }); 
    

    编辑:此代码仅适用于名称以字符串 foo 开头的输入元素 Example

    【讨论】:

    • 干杯,但我在同一页面上有其他类型的文本输入,我不想自动填充。
    • 好的,1秒,我会调整答案
    • 谢谢伙计,我接受了 Anurags 解决方案,但 +1 挂在那里 :)
    • 很高兴您找到了解决方案!这就是我们在这里的全部目的。
    【解决方案2】:

    jQuery 将无法通过 id $('#foo[1]') 进行选择,因为它包含 [],所以我选择第一个元素为 $('[id=foo[1]]')。然后获取所有下一个文本框,如果它们的 id 属性与foo[&lt;digits&gt;] 不匹配,则将它们过滤掉,然后应用与第一个相同的值,或者根据复选框状态清除它们。

    example

    $("#same").click(function() {
        var first = $('[id=foo[1]]');
        var next = first.nextAll(':text').filter(function() {
            return /foo\[\d+\]/.test(this.id);
        });
        if($(this).is(':checked')) {
            next.val(first.val());
        }
        else {
            next.val('');
        }   
    });​
    

    虽然这可行,但将 firstrest 等类添加到 HTML 中可能会更容易,这会使事情变得更容易。

    <input id="same" name="same" type="checkbox" />
    <input type="text" id="foo[1]" name="foo[1]" class="first" value="" />
    <input type="text" id="foo[2]" name="foo[2]" class="rest" value="" />
    <input type="text" id="foo[3]" name="foo[3]" class="rest" value="" />
    <input type="text" id="foo[4]" name="foo[4]" class="rest" value="" />
    <input type="text" id="foo[5]" name="foo[5]" class="rest" value="" />
    

    jQuery 代码然后简化为:

    $("#same").click(function() {
        if($(this).is(':checked')) {
            $('.rest').val($('.first').val());
        }
        else {
            $('.rest').val('');
        }   
    });​
    

    【讨论】:

    • 优秀的答案,非常感谢 :) 我正在使用第二种方法,因为它正是我知道但想不到的横向解决方案。干杯!
    • 当,阿努拉格,我想成为你!很好的答案。
    【解决方案3】:

    也许是这样的?

    http://jsbin.com/anone3/2/edit

    【讨论】:

    • 不错!即使我已经接受了答案,也给你 +1 :)
    猜你喜欢
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多