动态元素的javascript验证 [英] javascript validation for dynamic element

查看:75
本文介绍了动态元素的javascript验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何验证动态创建的文本输入?

How can I validate dynamically created text inputs?

我有一个添加更多链接创建新链接,以及一个删除它们的链接。每个人都有一个唯一的ID。

I have an "add more" link that creates new ones, and a link to remove them. Each one has a uniqe ID.

此外,必须至少填写两个文本框。

Also, at least two text boxes must be filled.

推荐答案

写了一篇博客文章,解释了如何动态地向表单添加输入,同时为jQuery Validate插件添加验证规则。

I wrote a blog post explaining how to dynamically add inputs to a form, and simultaneously add validation rules for the jQuery Validate plugin.

在我的例子中,它是头盔的订单:

In my example, it was an order form for helmets:

//Each set of helmet inputs gets unique IDs
function newHelmetInputs(i){
var inputSet = ''; 
inputSet += '<label for="helmet'+ i +'color">Helmet '+ i +' Color</label>'
inputSet += '<input id="helmet'+ i +'color" name="helmet['+ i +'][color]"/>'
inputSet += '<label for="helmet'+ i +'size">Helmet '+ i +' Size</label>'
inputSet += '<input id="helmet'+ i +'size" name="helmet['+ i +'][size]"/>'
return inputSet;
}

//Actually adding them to the page
$('#addhelmet').click(function(){
var i = nextNumber(); //nextNumber() is a closure - see my blog for details
var newInputs = newHelmetInputs(i); //i is used above in IDs
$(this).before(newInputs);
('#helmet' + i + 'size').rules('add', {digits: true}); //matching validation rule
});

博客文章详细介绍,并解释了如何使用PHP处理此问题。

The blog post goes into more detail, and also explains how to process this with PHP.

至于必须填写至少两个文本框的要求,我写了 jQuery Validate方法,以及一个类似的,表示要么填写本节中至少X个字段,要么完全跳过该部分。

As for the requirement that at least two textboxes must be filled, I wrote a jQuery Validate method for that, and a similar one that says "either fill at least X of the fields in this section, or skip the section entirely."

因此,例如,如果您的表单允许人们订购三明治,并且每个三明治都有面包和填充的输入,您可以动态添加字段他们想订购的三明治。他们不需要为#3三明治填写任何东西,但如果他们这样做,他们必须给你面包和馅料类型。

So, for example, if your form lets people order sandwiches, and each sandwich has an input for bread and filling, you can dynamically add fields for as many sandwiches as they want to order. They don't have to fill in anything for sandwich #2, but if they do, they have to give you both the bread AND the filling type.

这篇关于动态元素的javascript验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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