2017-03-23 82 views
2

我有html輸入,用戶可以在其中輸入任何文本。此外,用戶還可以添加更多的輸入和插入任何文字太:動態數據問題上的jquery .each()

<div class="u-form-group" id="1" style="margin-top:50px;"> 
    <input type="text" placeholder="Word in Native Language" name="native_word" id="native_word" class="niceinput" /> 
    <input type="text" placeholder="Translation" name="learn_word" id="learn_word" class="niceinput" /> 
</div> 

所以,想象一下有幾個比較相似.U形組塊。

點擊按鈕點擊我有.each,它從每個塊收集#native_word的值。

$("#btn-save").click(function() { 
    $(".canvas .u-form-group").each(function() { 
     var id_div = ".u-form-group#"+$(this).attr('id')+" #native_word"; 
     alert($(''+id_div).val()); 
    }); 
}); 

在點擊的結果,我只收到第一個輸入(這是手動寫入代碼)的有效值。從別人我只得到 - 「未識別」。

如何使它正常工作並從動態加載的輸入中收集值?

+0

你複製HTML IDS?因爲這不是一個好的做法 –

回答

1

您可以使用jQuery的find功能找到each回調內部的native_word輸入,然後用.val()訪問值:

$("#btn-save").click(function() { 
 
    $(".canvas .u-form-group").each(function() { 
 
    var nativeWord = $(this).find("input#native_word"); 
 
    console.log(nativeWord.val()); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="canvas"> 
 
    <div class="u-form-group" id = "1" style = "margin-top:50px;"> 
 
    <input type="text" placeholder="Word in Native Language" name="native_word" id="native_word" class="niceinput" /> 
 
    <input type="text" placeholder="Translation" name="learn_word" id="learn_word" class="niceinput" /> 
 
    </div> 
 
    <div class="u-form-group" id = "2" style = "margin-top:50px;"> 
 
    <input type="text" placeholder="Word in Native Language" name="native_word" id="native_word" class="niceinput" /> 
 
    <input type="text" placeholder="Translation" name="learn_word" id="learn_word" class="niceinput" /> 
 
    </div> 
 
</div> 
 
<button id="btn-save">Save</button>

+0

非常感謝!真的很好 – user1584043

1

你不應該重複的ID。嘗試使用類,它的作品。

$("#btn-save").click(function() { 
 
    $(".canvas .u-form-group").each(function() { 
 
    alert($(this).find('.niceinput-native').val()); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="canvas"> 
 
    <div class="u-form-group" id="1" style="margin-top:50px;"> 
 
    <input type="text" placeholder="Word in Native Language" name="native_word" class="niceinput-native" /> 
 
    <input type="text" placeholder="Translation" name="learn_word" class="niceinput-translation" /> 
 
    </div> 
 
    <div class="u-form-group" id="2" style="margin-top:50px;"> 
 
    <input type="text" placeholder="Word in Native Language" name="native_word" class="niceinput-native" /> 
 
    <input type="text" placeholder="Translation" name="learn_word" class="niceinput-translation" /> 
 
    </div> 
 
</div> 
 
<button id="btn-save">Save</button>