如何根据单击的提交按钮选择父表单? [英] How do I select the parent form based on which submit button is clicked?

查看:89
本文介绍了如何根据单击的提交按钮选择父表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页,上面有3种表格.不是嵌套的,只是一个接一个的(它们几乎是相同的,只是一个不同的隐藏变量).一个用户只会填写一张表格,我想只用一个JS脚本来验证/等所有表格.

I have a web page with 3 forms on it. Not nested, just one after the other (they are almost identical, just one hidden variable that's different). A user will only fill in one form, and I'd like to validate/etc all the forms with only one JS script.

那么,当用户单击表单#1的提交按钮时,如何使我的js脚本仅处理表单1中的字段?我收集到它与$(this).parents有关,但是我不确定该如何处理.

So how, when a user clicks the submit button of form#1, do I make my js script only deal with the fields in form1? I gather it has something to do with $(this).parents , but I am not sure what to do with it.

我的验证脚本(我在其他地方使用过,只有一种形式)看起来像这样:

My validation script (which I used elsewhere, with only a single form) looks something like so:



$(document).ready(function(){
    $("#submit").click(function(){
        $(".error").hide();
        var hasError = false;

        var nameVal = $("#name").val();
        if(nameVal == '') {
            $("#name").after('Please enter your name.');
            hasError = true;
        }


        if(hasError == false) {blah blah do all the processing stuff}

所以我需要用$(this).parents('form').name.val()替换$(#name").val()之类的东西吗?还是有更好的方法来解决这个问题?

So do I need to replace things like $("#name").val() with $(this).parents('form').name.val() ? Or is there a better way to go about this?

谢谢!

推荐答案

您可以选择以下形式:

$("#submit").click(function(){
    var form = $(this).parents('form:first');
    ...
});

但是,通常最好将事件附加到表单本身的Submit事件上,因为即使在通过按下以下字段之一中的Enter键提交时也会触发该事件:

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

要选择表单内的字段,请使用表单上下文.例如:

To select fields inside the form, use the form context. For example:

$("input[name='somename']",form).val();

这篇关于如何根据单击的提交按钮选择父表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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