2010-04-13 33 views
1

問候,jQuery來填充基於第一輸入值陣列命名錶單域,其中域的數目是未知的

我有一個可變數目的輸入,這簡化版本的看起來像這樣一種形式:

<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());上找到任何變化。

幫助!

回答

3

jQuery將失敗的ID $('#foo[1]'),因爲它包含[]選擇,所以我選擇第一個元素爲$('[id=foo[1]]')。然後獲取所有下一個文本框,然後過濾出它們的id屬性是否與foo[<digits>]不匹配,然後應用與第一個相同的值或根據複選框狀態清除它們。

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(''); 
    } 
});​ 
+0

非常好的答案,非常感謝:)我使用第二種方法,因爲它正是我所知道的那種側向解決方案,但卻無法想象。乾杯! – da5id 2010-04-13 01:40:31

+0

Dang,Anurag,我想成爲你!很好的答案。 – Marcus 2010-07-28 20:34:11

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開始 Example

+0

歡呼聲,但我有我不希望自動填充在同一頁面上鍵入文本的其他投入。 – da5id 2010-04-13 01:10:27

+0

好吧,1秒鐘,我會調整我的答案 – Jon 2010-04-13 01:18:15

+1

謝謝隊友,我接受Anurags解決方案,但+1掛在那裏:) – da5id 2010-04-13 01:41:06

相關問題