从序列化数组中提取值 - 表单验证

时间:2018-02-21 17:00:21

标签: javascript jquery html spring-boot

我有一张表格:

<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')等但似乎无法让它工作。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:2)

在评论中与您交谈后,这是form_data var:

的输出
Array(4) 
    0 : {name: "id", value: "0"} 
    1 : {name: "email", value: "test@uni.ac.uk"} 
    2 : {name: "uniName", value: "aUni"} 
    3 : {name: "adminName", value: "anAdmin"}

根据你的HTML,它指的是你的“字段”attr而不是你的“名字”,所以要选择它们,改变它:

var element = $('#' + form_data[input]['name']);

到此:

var element = $("input[field='" + form_data[input]['name'] + "']");

或者这个(正如@Taplar评论中所建议的那样):

var element = $('input').filter('[field="'+ form_data[input]['name'] +'"]');

你可以吗?