[英]Target content generated dynamically with jquery
So i have 10 inputs dynamically created and i want do to a simple validation if they are not blank, the problem is that the code that i have does not work for these because they are not created at the page load. 所以我有10个输入动态创建,我想要做一个简单的验证,如果它们不是空白,问题是我的代码不适用于这些因为它们不是在页面加载时创建的。
how can i achieve this? 我怎么能实现这个目标? Thx in advance
Thx提前
function submitForm() {
for(var i = 0; i < 10 ; i++){
if($("#input"+i).value == null){
alert("False!!");
}
}
}
You should use val()
to check input value instead of value
您应该使用
val()
来检查输入值而不是value
(function() { var i = 0; $('button').click(function() { $('body').append('<input type="text" id="input-' + i + '">'); i++; }); $('input[type="submit"]').click( function() { $('input[type="text"]').each(function() { if ($(this).val() == '') { alert($(this).attr('id') + ' is empty'); } }); }); })();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="submit" value="Submit"> <button>Create input</button>
You should use .val()
instead of .value
. 您应该使用
.val()
而不是.value
。 I also suggest using .each()
. 我还建议使用
.each()
。 Also when input
is empty, its value is ""
not null
. 此外,当
input
为空时,其值为""
不为null
。
for(var i = 0; i < 10 ; i++) {
if($("#input"+i).val() == "") {
alert($("#input"+i).attr('id') + " is empty!")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.