[英]Validating newly created inputs
我正在使用带有动态创建输入的小型附件形式。
这些新输入是通过以下方式创建的:
function addAttachmentRow() {
var htmlRow = '<tr><td><input type="text" name="file_name[]"></td></tr>';
$("#attachment_list").append(htmlRow);
}
并且我正在尝试准备验证功能,但是这段代码:
$( document ).ready(function() {
$('input[name^="file_name"]').each(function() {
$(this).keydown(function(){
if ($(this).val().length < 2) {
$(this).css("background-color", "#FFCCCC");
$(this).css("border", "1px solid #665252");
$(this).css("color", "#B20000");
} else {
$(this).css("background-color", "#F5FFEB");
$(this).css("border", "1px solid #5CE65C");
$(this).css("color", "#145214");
}
});
});
});
但它仅适用于静态创建的第一个元素。 它不影响单击“ addAttachmentRow”并添加新输入时创建的元素。
更改为
$('input[name^="file_name[]"]').each(function() {
也无济于事,我只需要在输入名称中使用[]即可。
有任何想法吗?
提前致谢。
是。 它发生了。 它不会选择带有该代码的元素。 您将需要使用$(document).on方法代替此方法。
解决方案 :
使用此代码
$(document).on('event', 'selector', function() {
// code
});
例如
$(document).on('each', 'input[name^="file_name[]"]', function() {
alert('Event fired!');
});
您需要将事件与文档绑定以获取动态元素:
$(function(){
$(document).on('keydown', 'input[name^="file_name"]', function(e) {
/* to do here */
});
});
试试这个演示:
$(function() { $(document).on('keydown', 'input[name^="file_name"]', function(e) { var err = 2 > $.trim(this.value).length; $(this).toggleClass('rest', !err).toggleClass('err', err); }); }); function addAttachmentRow() { var htmlRow = '<tr><td><input type="text" name="file_name[]"></td></tr>'; $("#attachment_list").append(htmlRow); }
.rest { background-color: #F5FFEB; border: 1px solid #5CE65C; color: #145214; } .err { background-color: #FFCCCC; border: 1px solid #665252; color: #B20000; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type='button' value='Add' onclick='addAttachmentRow()' /> <table id='attachment_list'> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.