jQuery 如何根据单击的提交按钮选择父表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/311579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:56:30  来源:igfitidea点击:

How do I select the parent form based on which submit button is clicked?

jqueryforms

提问by Eran Galperin

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.

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

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.

那么,当用户单击form#1 的提交按钮时,如何让我的js 脚本只处理form1 中的字段?我认为它与 $(this).parents 有关,但我不确定如何处理它。

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}

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?

那么我是否需要用 $(this).parents('form').name.val() 替换 $("#name").val() 之类的东西?或者有没有更好的方法来解决这个问题?

Thanks!

谢谢!

回答by Eran Galperin

You can select the form like this:

您可以像这样选择表单:

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

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:

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

$('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();

回答by TC0072

I found this answer when searching for how to find the form of an input element. I wanted to add a note because there is now a better way than using:

我在搜索如何找到输入元素的形式时找到了这个答案。我想添加一个注释,因为现在有一种比使用更好的方法:

var form = $(this).parents('form:first');

I'm not sure when it was added to jQuery but the closest() method does exactly what's needed more cleanly than using parents(). With closest the code can be changed to this:

我不确定它是何时添加到 jQuery 中的,但最接近的() 方法确实比使用parents() 更干净地完成了所需的工作。使用最接近的代码可以更改为:

var form = $(this).closest('form');

It traverses up and finds the first element which matches what you are looking for and stops there, so there's no need to specify :first.

它向上遍历并找到与您要查找的内容匹配的第一个元素并在那里停止,因此无需指定 :first。

回答by redsquare

To get the form that the submit is inside why not just

要获得提交在里面的表单,为什么不只是

this.form

Easiest & quickest path to the result.

获得结果的最简单和最快的途径。

回答by charles

i used the following method & it worked fine for me

我使用了以下方法,它对我来说很好用

$('#mybutton').click(function(){
        clearForm($('#mybutton').closest("form"));
    });

$('#mybutton').closest("form")did the trick for me.

$('#mybutton').closest("form")帮我解决了这个问题。

回答by Lathan

Eileen: No, it is not var nameVal = form.inputname.val();. It should be either...

艾琳:不,不是var nameVal = form.inputname.val();。应该是要么...

in jQuery:

在 jQuery 中:

// you can use IDs (easier)

var nameVal =  $(form).find('#id').val();

// or use the [name=Fieldname] to search for the field

var nameVal =  $(form).find('[name=Fieldname]').val();

Or in JavaScript:

或者在 JavaScript 中:

var nameVal = this.form.FieldName.value;

Or a combination:

或组合:

var nameVal = $(this.form.FieldName).val();

With jQuery, you could even loop through all of the inputs in the form:

使用 jQuery,您甚至可以遍历表单中的所有输入:

$(form).find('input, select, textarea').each(function(){

  var name = this.name;
  // OR
  var name = $(this).attr('name');

  var value = this.value;
  // OR
  var value = $(this).val();
  ....
  });