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..
我如何使用.on()和.each()一起使用?我用Google搜索没有运气..提前谢谢..
2 个解决方案
#1
4
Your code is pretty much fine, but get rid of the return false;
. It stops the .each()
loop after the first input is hit.
你的代码非常好,但摆脱了返回false;在第一次输入命中后,它会停止.each()循环。
#2
1
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..
它应该不是问题,除非当你点击页面时页面上没有元素..也因为你返回false;当该字段为空时,只有第一个文本框将被赋予边框..其他将被清空,即使是空的..
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
另请查看此工作示例... FIDDLE
#1
4
Your code is pretty much fine, but get rid of the return false;
. It stops the .each()
loop after the first input is hit.
你的代码非常好,但摆脱了返回false;在第一次输入命中后,它会停止.each()循环。
#2
1
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..
它应该不是问题,除非当你点击页面时页面上没有元素..也因为你返回false;当该字段为空时,只有第一个文本框将被赋予边框..其他将被清空,即使是空的..
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
另请查看此工作示例... FIDDLE