1

问候,

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

<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());工作中得到任何变化。

帮助!

4

3 回答 3

3

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

例子

$("#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('');
    }   
});​

尽管这可行,但将诸如first和之类的类添加rest到 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('');
    }   
});​
于 2010-04-13T01:20:59.313 回答
2
    $("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 开头的输入元素 示例

于 2010-04-13T01:09:12.287 回答
2

也许是这样的?

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

于 2010-04-13T01:58:26.083 回答