如何使用jQuery创建动态表单? [英] How to create a dynamic form using jQuery?
问题描述
我已经看到了很多动态添加行或字段的帮助,但我有兴趣控制相互依赖的字段。
I've seen a lot of help for dynamically adding rows or fields, but I'm interested in controlling fields that are dependent on one another.
例如,我有一个包含3个用户输入的表单:
For example, I have a form with 3 user inputs:
<select id="foo">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
如果设置了 #foo
的值至 1
,我想启用 #bar
。
When #foo
's value is set to 1
, I'd like to enable #bar
.
<!-- by default, bar should be disabled -->
<select id="bar">
<option value="something_1">Something 1</option>
<option value="something_2">Something 2</option>
<option value="other">Other...</option>
</select>
设置 #bar
的值至其他
,我想启用 #baz
。
When #bar
's value is set to other
, I'd like to enable #baz
.
<!-- by default, baz should be disabled -->
<textarea id="baz"></textarea>
我的目标
我想编写一个小插件的指导,这个插件可以轻松创建带有依赖关系的表单输入。
My Goal
I'd like to some guidance on writing a small plugin that allows easy creation of form inputs with dependencies.
简洁的语法。有什么办法可以添加html属性助手来帮助jQuery插件自动化吗?
可预见的问题
I'd like short, concise syntax. Is there a way I could add html attribute helpers to aid the jQuery plugin in "automating" things?
- 如果
#foo
设置为Yes,则#bar
为设置为其他,然后#foo
设置为否,我会希望#bar
的依赖关系停用/隐藏。 - 输入被启用/禁用和/或可见/隐藏;具有为元素定义自定义行为的能力会很好。
- If
#foo
is set to "Yes", then#bar
is set to "other", then#foo
is set to "No", I will want#bar
's dependencies deactivated/hidden as well. - Inputs are enabled/disabled and/or visible/hidden; Having the ability to define custom behaviors for elements would be nice.
重塑车轮
如果有一个插件可以做这种事情,请告诉我!我似乎无法找到一个...
Reinventing the Wheel
If there's a plugin out there that does this kind of thing, let me know! I couldn't seem to find one...
推荐答案
一个快速插件
(function($){
$.fn.inputDependsOn = function(id, values, options){
var self = this;
// methods
this.disable = function(e){
return e.addClass(options.cssClass).attr({disabled: true}).trigger("disable");
};
this.enable = function(e){
return e.removeClass(options.cssClass).attr({disabled: null}).trigger("enable");
};
// options
options = $.extend({}, $.fn.dependsOn.defaults, options || {});
var parent = $(id);
this.each(function(){
var child = $(this);
// parent binds
parent
.bind("change", function(){
var v = parent.val();
if(parent.is(":not(:disabled)") && v in values){
self[values[v]](child);
}
else {
self[options.init](child);
}
child.change();
})
.bind("disable", function(){
self.disable(child);
})
;
});
// init
parent.change();
return this;
};
$.fn.dependsOn.defaults = {
init: "disable",
cssClass: "disabled"
};
})(jQuery);
在原始问题中使用HTML,目标可以通过以下方式实现:
Using the HTML in the original question, goal can be accomplished with:
$("#bar").inputDependsOn("#foo", {"1": "enabled"});
$("#baz").inputDependsOn("#bar", {"other": "enable"});
这个插件将在这里进行维护和更新:
github.com/macek/ jquery-input-depends-on
这篇关于如何使用jQuery创建动态表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!