Per Jeevan:由于您无法确定用户提交了多少项目,我会选择一种方法,让所有新项目都具有唯一的类,例如dynamicAddedItems
.
正如 Jeevan 已经说过的,您可以在 form 标签中添加以下内容,以防止它在返回时提交false
。
<form onsubmit="return validate();"></form>
使用 javascript:
function validate(){
var elems = document.getElementsByClassName( 'dynamicAddedItems' );
var allgood = true;
//Loop through all elements with this class
for( var i = 0; i < elems.length; i++ ) {
if( !elems[i].value || !elems[i].value.length ) {
elems[i].className += " error";
allgood = false;
} else {
elems[i].className = "item_text_area item_name dynamicAddedItems";
}
}
//If any element did not meet the requirements, prevent it from being submitted and display an alert
if( !allgood ) {
alert( "Please fill in all the required fields." );
return false;
}
//Otherwise submit the form
return true;
}
如果字段为空,此脚本将添加错误类并阻止提交表单。如何显示具有此类的字段取决于您。