简体   繁体   English

我一般如何使用jQuery遍历表单中的输入元素?

[英]How do I generically loop through input elements in a form using jQuery?

I'm trying to loop through the input elements in a form using jQuery so that I can do some lightweight client-side validation. 我正在尝试使用jQuery遍历表单中的输入元素,以便可以进行一些轻量级的客户端验证。 I'm using Django to generate the pages server side and the problem I'm having is that the particular page has many forms dynamically generated so I don't know the id of them before hand. 我正在使用Django来生成页面服务器端,而我遇到的问题是特定页面具有动态生成的多种形式,因此我事先不知道它们的ID。 If I did I could easily do the validation. 如果我做了,我可以轻松进行验证。

So in my javascript I'm trying to capture the submit action of the form and when that's found, somehow get the input elements so that I can check the parameters. 因此,在我的JavaScript中,我试图捕获表单的Submit操作,当找到该表单时,以某种方式获取输入元素,以便我可以检查参数。 Here's what I've tried amongst other things: 这是我尝试过的其他方法:

$(".s-inputs").submit(function(event){      
  $(this).filter(':input').each(function(){
    console.log("Doesn't work");
  });
  event.preventDefault();
});

I tried including the django code that generates the html forms below but something in the templating system was throwing off Stack Overflow's formatting of it. 我试过在下面包含生成html表单的django代码,但模板系统中的某些内容使Stack Overflow的格式无法正常运行。 I don't think it would have been very instructive anyway. 无论如何,我认为这不会很有启发性。 Essentially my html is just an arbitrary number of forms on the page each with an arbitrary number of inputs, all dynamically generated server side. 本质上,我的html只是页面上的任意数量的表单,每个表单具有任意数量的输入,所有表单都是动态生成的服务器端。 The only thing they share in common is the class "s-inputs." 它们唯一的共同点是“ s-inputs”类。

Thanks for any help. 谢谢你的帮助。

You should use find() , not filter() : 您应该使用find() ,而不是filter()

$(this).find(':input').each(function(){
  console.log("Doesn't work");
});

filter() attempts to filter the currently selected element(s) (which is currently just your form element) and remove anything which isn't what is being filtered on. filter()尝试过滤当前选择的元素(当前只是您的form元素),并删除所有不被过滤的元素。 This will return nothing, as your form element isn't matched by :input . 这将不返回任何内容,因为您的form元素与:input不匹配。

find() on the other hand searches for any matching selector contained within the currently selected elements. 另一方面, find()搜索当前选定元素中包含的任何匹配选择器。 This will match any matching :input element contained within your form . 这将匹配form包含的任何匹配的:input元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM