我有一个表格:
<form role="form" id="emailForm" action="#" th:action="@{/emailSubmission}" th:object="${university}" method="post">
<div class="form-group">
<input type="hidden" th:field="*{id}" ></input>
<p>
<label for="emailID"><span class="glyphicon glyphicon-envelope"></span> Email</label>
<input type="email" class="form-control" name="emailID" id="emailID" field="email" th:field="*{email}" placeholder="Enter email"></input></p>
<p>
<label for="uniID"><span class="glyphicon glyphicon-book"></span> University Name</label>
<input type="text" class="form-control" name="uniID" id="uniID" field="uniName" th:field="*{uniName}" placeholder="Enter University Name"></input></p>
<p>
<label for="adminID"><span class="glyphicon glyphicon-user"></span> Administrator name</label>
<input type="text" class="form-control" name="adminID" id="adminID" field="adminName" th:field="*{adminName}" placeholder="Enter Aministrator Name"></input></p>
</div>
<button type="button" id="submitButton" class="btn btn-default btn-success btn-block" data-dismiss="modal" ><span class="glyphicon glyphicon-check"></span> Register</button>
</form>
还有一些jQuery:
//submit form validation
$("#submitButton").click(function(event) {
var form_data = $("#emailForm").serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $('#' + form_data[input]['name']);
var valid = element.hasClass("is-valid");
if (!valid) {
error_free = false;
}
}
if (!error_free) {
event.preventDefault();
} else {
sendEmail();
};
});
我的问题是:
var element=$('#' + form_data[input]['name']);
它试图返回$('#emailID')等,但似乎无法正常工作。任何帮助,将不胜感激。
最佳答案
在评论中与您交谈之后,这是您的form_data
var的输出:
Array(4)
0 : {name: "id", value: "0"}
1 : {name: "email", value: "[email protected]"}
2 : {name: "uniName", value: "aUni"}
3 : {name: "adminName", value: "anAdmin"}
根据您的HTML,它引用的是您的“字段”属性,而不是您的“名称”,因此要选择它们,请进行以下更改:
var element = $('#' + form_data[input]['name']);
对此:
var element = $("input[field='" + form_data[input]['name'] + "']");
或这个(如@Taplar的评论所建议):
var element = $('input').filter('[field="'+ form_data[input]['name'] +'"]');
可以吗
关于javascript - 从序列化数组中提取值-表单验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48911483/