Samuel Haaf Samuel Haaf - 2 months ago 8
HTML Question

get val() from dynamically generated text element

Okay, so I have some dynamically generated text boxes whose values aren't found when I call .val(). The text input that was rendered on page load will return a value with .val(), but all the rest will not.

If this example isn't sufficient to get an answer then I will edit the question with my actual code, but I've done my best to accurately simplify it.

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>

Answer

You should improve your selectors. Keeping an incrementing ID is usually a sign you're doing something wrong.

For instance...

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());
  })
}
Comments