I have some input text fields that are being generated on the fly (via javascript) by the user. I want those fields to accept integers only so I am using the alphanumeric plugin. The plugin works as expected on elements that already e开发者_运维技巧xist when the page loads but it does not work with the new on-the-fly elements. How can I live-bind the new elements to this plugin? Thanks!
Here is some sample code.
http://jsfiddle.net/ctown4life/tZPg4/780/
Simple quick fix - change:
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
to
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').numeric().appendTo(scntDiv);
Please notice that the dynamically inserted fields are all getting the same id. That's not good, you should either use a unique id for each input, or no id at all.
Here you go
http://jsfiddle.net/tZPg4/781/
You just need this
$('#addScnt').live('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv).find("input").numeric();
The issue is not because you are using live
, its because you are not running the numberic
plugin on the newly created input box.
live
will not help you here. You'll have to re-initiate the plugin whenever you add a new input:
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>')
.appendTo(scntDiv)
.find('input').numeric();
One way is just to call the alphanumeric plugin for your dynamic inputs:
$('#addScnt').live('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
$('#p_scents p:last input').numeric(); // Added this line...
return false;
});
Just call the .numeric() method on the newly appended input field. After doing the .appendTo(scntDiv), you call:
scntDiv.children('p:last .intonly').numeric();
Full code:
http://jsfiddle.net/ebiewener/tZPg4/782/
精彩评论