从动态生成的文本元素中获取val()

时间:2016-09-17 09:11:47

标签: jquery html

好的,所以我有一些动态生成的文本框,当我调用.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>

2 个答案:

答案 0 :(得分:0)

这就是我解决问题的方法。 @Niet,你的建议是使用更好的选择器来帮助你。我将努力使用不需要顺序识别的选择器,但这将使它今天起作用。

Date       TypeA_ValueA   TypeA_ValueB  TypeB_ValueA TypeB_ValueB
09-02-2016  3             5             6            7

答案 1 :(得分:-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());
  })
}