jquery / js - 我如何根据点击提交按钮来选择父窗体? [英] jquery/js -- How do I select the parent form based on which submit button is clicked?

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

问题描述

我有一个包含3个表格的网页。不是嵌套的,只是一个接一个(它们几乎完全相同,只是一个隐藏变量不同)。用户将只填写一个表单,并且我想用一个JS脚本来验证/ etc所有表单。

所以,当用户点击提交表单#1的按钮,我是否让我的js脚本只处理form1中的字段?我收集它与$(this).parents有关,但我不知道如何处理它。



我的验证脚本(我在别处使用过,只有一个表单)看起来像这样:

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

var nameVal = $(#name)。val();
if ('请输入您的姓名');
hasError = true;
}
$ b $(#name)。 b
if(hasError == false){blah blah做所有处理的东西}


$ b $因此,我需要用$(#name).val()替换$(this).parents('form')。name.val()吗?还是有更好的方法可以去关于这个?



谢谢!

解决方案

像这样:

  $(#submit)。click(function(){
var form = $(这个).parents('form:first');
...
));

然而,将事件附加到表单本身的提交事件,因为即使通过按下某个字段的回车键提交,它也会触发:

  $('form#myform1')。submit(function(e){
e.preventDefault(); //防止正常提交动作
var form = this;
// ...处理表单提交
});

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

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


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.

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}

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?

Thanks!

解决方案

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:

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

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

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