2016-09-17 51 views
-3

好吧,所以我有一些動態生成的文本框,當我調用.val()時,其值不會被找到。在頁面加載時呈現的文本輸入將使用.val()返回一個值,但其餘的都不會。從動態生成的文本元素獲取val()

如果這個例子不足以得到答案,那麼我將用我的實際代碼編輯這個問題,但我已經盡力準確地簡化它。

JQuery的:

numBoxes = 0 

function newText(){ 
    numBoxes++ 
    $('<div id="' + numBoxes + '"><input id="soft_text_' + numBoxes + 
    '" type="text"></div>').insertBefore($('button#new')) 
} 

function logHard(){ 
    console.log($('input#hard_text').val()) 
} 

function logSoft(){ 
    $('div').each(function(){ 
    console.log($('input#soft_text_' + this.id).val()) 
    }) 
} 

HTML:

<html><body> 
<input id="hard_text" type="text" name="first_text"> 
<button id="new" onclick="newText()">Add new text box</button> 
<button onclick="logHard()">Log first text box</button> 
<button onclick="logSoft()">Log new text boxes</button> 
</body></html> 
+0

可能是因爲裏面沒有文字? – putvande

+0

*「我已盡力準確地簡化它。」*簡化很好,但它應該是[mcve]。在這種情況下,由於它是基於瀏覽器的技術,因此使用Stack Snippets('<>'工具欄按鈕)將其設置爲**可運行** MCVE。 –

+0

可能這是你需要的[請檢查這個鏈接](http://stackoverflow.com/questions/38322394/jquery-copy-dynamically-added-table-row-values-into-next-row/38328193#38328193 ) –

回答

-1

你應該提高你的選擇。保持遞增的ID通常表示你做錯了什麼。

例如...

function newText(){ 
    $('<div class="addedbox"><input type="text"></div>').insertBefore($('button#new')); 
} 
function logHard(){ 
    console.log($('input#hard_text').val()); 
} 
function logSoft(){ 
    $('div.addedbox>input').each(function(){ 
    console.log($(this).val()); 
    }) 
} 
+0

誰能說這解決了OP的問題?這可能是(長)評論。 – putvande

+0

雖然我同意ID有點狡猾,但不太可能會解決任何實際問題。 –

+0

感謝您將我推薦給'>'。 – v4gil

0

這是我如何解決了這個問題。 @Niet,你的建議是使用更好的選擇器。我將努力使用那些不需要在將來進行順序識別的選擇器,但這會使它在今天工作。

function logSoft(){ 
    $('div').each(function(){ 
    console.log($('div#' + this.id + ' > input').val()) 
    }) 
}