jQuery验证具有多个表单的页面上的特定表单 [英] Jquery validating a specific form on a page with multiple forms

查看:62
本文介绍了jQuery验证具有多个表单的页面上的特定表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请提供一些建议. 我正在尝试验证多表单页面,但不确定如何在jquery选择器中指定表单:

Some suggestions or advice please. I'm trying to validate a multi-form page but I'm not sure how to specify the form in jquery selector:

<form id="form_a">
    <label>First Name</name><input type="text" class="required"><br>
    <label>Email</label><input type="text" class="required">
<button onclick="validate('form_a')">Submit</button>
</form>

<form id="form_b">
    <label>Serial No </name><input type="text" class="required"><br>
    <label>Brand </label><input type="text" class="required">
<button onclick="validate('form_b')">Submit</button>
</form>

<form id="form_c">
    <label>First Name</name><input type="text" class="required"><br>
    <label>Email</label><input type="text" class="required">
<button onclick="validate('form_c')">Submit</button>
</form>

<script>
function validate(whichform) {

    $(whichform+" .required").each(function(i){
        if ($(this).val().indexOf() < 0){
        alert("null value detected")
        $(this).css("border","1px solid red")
        }
    });

}
</script>

推荐答案

在这种情况下,您要将id传递给方法,但没有使用id选择器,如果发生以下情况,您还必须从事件处理程序返回false您要阻止提交表单

In your caase you are passing the id to the method, but you are not using the id selector, also you will have to return false from the event handler if you want to prevent the submission of the form

<button onclick="return validate('form_c')">Submit</button>

如此

function validate(whichform) {
    var valid = true;
    // whichform is the id so use id selector here
    $('#' + whichform + " .required").each(function (i) {
        if ($(this).val().length == 0) {
            alert("null value detected")
            $(this).css("border", "1px solid red")
            valid = false;
        } else {
            $(this).css("border", "")
        }
    });
    //return the valid state
    return valid;
}

演示:小提琴

但是,更多的jQuerish解决方案是使用jQuery事件处理程序之类的

But a more jQuerish solution will be is to use jQuery event handlers like

<form id="form_a">
    <label>First Name</label>
    <input type="text" class="required" />
    <br/>
    <label>Email</label>
    <input type="text" class="required" />
    <button>Submit</button>
</form>

然后

jQuery(function () {
    $('form').submit(function () {
        var valid = true;
        // whichform is the id so use id selector here
        $(this).find(".required").each(function (i) {
            if ($(this).val().length == 0) {
                alert("null value detected")
                $(this).css("border", "1px solid red")
                valid = false;
            } else {
                $(this).css("border", "")
            }
        });
        //return the valid state
        return valid;
    })
})

演示:小提琴

这篇关于jQuery验证具有多个表单的页面上的特定表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆