Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery-2相同的表单,只想验证提交的表单_Javascript_Jquery_Forms - Fatal编程技术网

Javascript jQuery-2相同的表单,只想验证提交的表单

Javascript jQuery-2相同的表单,只想验证提交的表单,javascript,jquery,forms,Javascript,Jquery,Forms,我有两个具有相同类的相同表单,我只想检查提交表单的字段是否为空,而不是两个表单 表格HTML: <form class="booking-form"> <input type="text" name="pickup-address" class="pickup-address" /> <button type="button" class="bookingbutton"> <span>Reserve Now<

我有两个具有相同类的相同表单,我只想检查提交表单的字段是否为空,而不是两个表单

表格HTML:

<form class="booking-form">

    <input type="text" name="pickup-address" class="pickup-address" />

    <button type="button" class="bookingbutton">
        <span>Reserve Now</span>
    </button>

</form>
我使用的代码工作正常,但它检查两个表单,我只希望它检查单击提交按钮的表单


我知道我可以给每个表单一个unqiue类,但这不是一个选项,所以我可以使用$(this)来检查如何仅检查单击提交按钮的表单表单?

使用jQuery可以从单击的元素上下遍历DOM。在这种情况下,您可以尝试使用遍历到最近的
.booking表单
,然后使用该表单搜索您的
输入

我还建议在
input
上添加
required
属性,以便浏览器也提供一些关于元素的反馈

$(".booking-form").on('click', '.bookingbutton', function () {
    // find the closest form, because we have delegated the event, $(this) refers to the .bookingbutton element
    var form = $(this).closest('.booking-form');
    // check we found a form
    if(form.length === 0) return;

    // search within the found form for the .pickup-address
    if ( form.find(".pickup-address").val() == '') {        
        alert('Please enter a pickup location');
        return false;
    }
});

作为替代建议,您可以切换
的可见性或
禁用状态。bookingbutton
基于任何/所有必填字段的内容

这两种表单是否在同一页面上?因为
id
s对于每个页面都应该是唯一的,这是一个非常好的简单解决方案,感谢您的帮助!
$(".booking-form").on('click', '.bookingbutton', function () {
    // find the closest form, because we have delegated the event, $(this) refers to the .bookingbutton element
    var form = $(this).closest('.booking-form');
    // check we found a form
    if(form.length === 0) return;

    // search within the found form for the .pickup-address
    if ( form.find(".pickup-address").val() == '') {        
        alert('Please enter a pickup location');
        return false;
    }
});