Identifying dynamically generated elements
In the following code,
<script>
开发者_C百科 function val()
{
//get alltextarea to validate
}
$(document).ready(function() {
var html= '<form>'
html += '<textarea name="test" id="test"';
html += '<textarea name="test1" id="test1"';
html += 'form';
$('#get_div').append();
});
</script>
<div id= "get_div"></div>
<input type="button" onclick="val();"
The two textareas are dynamically generated.Now how to validate it in function val.When i do $('#test').val() or document.getElementbyId(test).value I could not find the values of the textareas
Thanks..
You're not generating valid HTML, there are a few problems:
- The
<textarea>
elements aren't closed. - The
<form>
element isn't closed - The
onclick
isn't rigged up correctly (bettter done via jQuery anyway)
Here's a corrected version with those changes that works:
jQuery:
$(document).ready(function() {
var html= '<form>'
html += '<textarea name="test" id="test"></textarea>';
html += '<textarea name="test1" id="test1"></textarea>';
html += '</form>';
$('#get_div').append(html);
$("input").click(function() {
alert($('#test').val());
});
});
HTML:
<div id= "get_div"></div>
<input type="button" Value="TestBtn" />
See a demo here
You can't tell the difference intrinsically between dynamically created elements and those from ordinary markup. What I'd suggest you do is use a marker class so:
$(function() {
$("textarea").addClass("static");
...
});
Those text areas without the static class are dynamically created. This is of course a cooperative scheme as there is nothing stopping you from creating dynamic markup with the static class but, like I said, you can't do anything about that.
精彩评论