admin管理员组文章数量:1332395
I have the following code;
$('#btnSave').click(function (e) {
$("input:text").each(function (index, value) {
var el = $(this);
if (el.val().length == 0) { el.css('border', '1px solid red') }
return false;
});
});
Here, all the input text elements are dynamically created hence I can never validate whether they are empty or not..
How do I go and use .on()
with .each()
? I googled with no luck.. Thanks in advance..
I have the following code;
$('#btnSave').click(function (e) {
$("input:text").each(function (index, value) {
var el = $(this);
if (el.val().length == 0) { el.css('border', '1px solid red') }
return false;
});
});
Here, all the input text elements are dynamically created hence I can never validate whether they are empty or not..
How do I go and use .on()
with .each()
? I googled with no luck.. Thanks in advance..
-
That code should work as long as the elements are created before the button is clicked.
.on()
is used for attaching events. – James Kleeh Commented Sep 7, 2012 at 17:26 - This looks like it will work fine, what problem are you having? – BZink Commented Sep 7, 2012 at 17:27
- 2 Why do you return false every time each calls your function? – Rikki Commented Sep 7, 2012 at 17:31
- Thank you for your help.. btnSave was an asp button which was causing postback. When I turned it into a standard button, it somehow worked.. I don't know why but I'll check... – Subliminal Hash Commented Sep 7, 2012 at 17:33
2 Answers
Reset to default 4Your code is pretty much fine, but get rid of the return false;
. It stops the .each()
loop after the first input is hit.
jsFiddle example
It should not be a problem until and unless the elements are not on the page when you click on the page.. Also because you are returning return false ; when the field is empty only the first textbox will be given the border.. Others will be left out even when empty..
Try this
$(function() {
$('#btn1').on('click' , function() {
var inp = '';
for(var i=1;i< 6;i++){
inp += '<input type="text" id="txt' + i + '"/>'
}
$('.textboxes').append(inp);
var isError = false;
$("input:text").each(function (index, value) {
var el = $(this);
if (el.val() == '') {
el.addClass('error');
isError = true;
}
});
if(isError){return false;}
});
});
Also check this working example... FIDDLE
本文标签: javascriptRunning jQueryeach() on dynamically created elementsStack Overflow
版权声明:本文标题:javascript - Running jQuery.each() on dynamically created elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742282907a2446422.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论