使用jQuery根据下拉框值动态添加表单域(或fieldsets) [英] Using jQuery to dynamically add form fields (or fieldsets) based on a dropdown box value

查看:388
本文介绍了使用jQuery根据下拉框值动态添加表单域(或fieldsets)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我想要做的是根据下拉框中选择的值,让jQuery添加一些额外的字段集。例如,当页面加载时,下拉列表的默认值为1,并显示默认字段集。现在,如果用户在该下拉列表中选择了不同的值,则通过克隆应该相应地调整字段集的数量(我想这将是最佳解决方案)。这是我到目前为止:



下拉框代码...

 < select id =itemCountname =itemCount> 
< option value =1> 1 item< / option>
< option value =2> 2 items< / option>
< option value =3> 3 items< / option>
< option value =4> 4 items< / option>
< option value =5> 5 items< / option>
< option value =6> 6个项目< / option>
< / select>

... jQuery更改监听器...



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ (this).val();
$(#item_dup_1)。fieldsManage(itemCountVal);
});
});

...和函数本身(它实际上是基于一个jQuery插件,我以为是一个好的起点我需要):

  jQuery.fn.fieldsManage = function(number){
var clone ,
objTemplate = source.clone(true),
source = jQuery(this),
maxClones = number - 1,
clones = [];

if(clones.length< maxClones){
while(clones.length< maxClones){
clone = objTemplate.clone(true).insertAfter(clones [ .length - 1] || source);
clones.push(clone);
}
}

if(clones.length> maxClones){
// Fieldets删除功能在这里。
}
}

正在克隆的对象类似于< fieldset id =item_dup_1>< input>< input>< input>< / fieldset> 。我不认为有必要显示它的完整代码。



这个功能类似于第一次更改的魅力,但是如果用户再次更改值,则出现错误,而不是显示正确数量的字段集,它显示更多。看起来它正在计算从零开始所需的字段集数,而不考虑现在已经添加了这些字段,这是我的问题实际上。我也有一个功能(这里没有显示,只是为了保持问题清楚,尽可能短),将新的ID标识到克隆的字段集,以防止重复的ID,并且没有任何挂钩。


$ b我确信我做错了事情,但是我已经把头撞到墙上了两天了,试图找到没有运气的东西,任何帮助都会比感谢!



提前感谢

解决方案

我不像Nate B的解决方案。




  • 它需要一个额外的容器元素

  • 重新创建所有内容丢失已经输入的数据

  • 创建维护问题:字段集的html标记被重复(一次在HTML中,一次作为追加的字符串)

  • 创建对于fieldets(id不能从一个数字开始)的无效id为



这样做你想要的和类似于什么y呃做了只保留原始元素的数据属性中的ids(而不是保留可能使用大量内存的整个克隆对象)。保留已输入的所有值。如果您从相反,只生成两个新的字段集。以相反的顺序删除它们在哪里创建。

  jQuery.fn.fieldsManage = function(number){
var ele = $(this);
var clones = ele.data(克隆);
克隆=克隆?克隆:新数组(ele.attr(id));
if(clones.length< number){
var clone;
while(clones.length< number){
clone = ele.clone(true);
var id = clones [0] + clones.length;
clone.attr(id,id);
$(#+ clones [clones.length-1])。after(clone);
clones.push(id);
}
} else {
while(clones.length> number){
$(#+ clones.pop())。
}
}
ele.data(克隆,克隆);
}

$(document).ready(function(){
$(#itemCount)。change(function(){
$(# item_dup_1)。fieldsManage(this.value);
});
});


As the title says, what I am trying to do is to have jQuery add a number of extra fieldsets based on the value selected in a drop-down box. For example, when the page loads, the drop-down has a default value of 1, and the default fieldset is displayed. Now, if the user selects a different value in that drop-down, the number of fieldsets should be adjusted accordingly, through cloning (I suppose this would be the best solution). Here's what I have so far:

Drop-down box code ...

<select id="itemCount" name="itemCount">
 <option value="1">1 item</option>
 <option value="2">2 items</option>
 <option value="3">3 items</option>
 <option value="4">4 items</option>
 <option value="5">5 items</option>
 <option value="6">6 items</option>
</select>

... the jQuery change listener ...

$(document).ready(function() {
 $("#itemCount").change(function(){
  var itemCountVal = jQuery(this).val();
  $("#item_dup_1").fieldsManage(itemCountVal);
 });
});

... and the function itself (it is actually based on a jQuery plugin which I thought was a good starting point for what I need):

jQuery.fn.fieldsManage = function (number) {
  var clone,
  objTemplate = source.clone(true),
  source = jQuery(this),
  maxClones = number - 1,
  clones = [];

  if (clones.length < maxClones) {
    while (clones.length < maxClones) {
      clone = objTemplate.clone(true).insertAfter(clones[clones.length - 1] || source);
      clones.push(clone);
    }
  }

  if (clones.length > maxClones) {
    // Fieldsets removal function goes here.
  }
}

The object that is being cloned is something like <fieldset id="item_dup_1"><input><input><input></fieldset>. I don't think it is necessary to show the full code for it as well.

This works like a charm for the first change, but if the user changes the value again, that's when things go wrong, and instead of showing the correct number of fieldsets, it shows more. It looks like it is calculating the number of fieldsets needed starting from scratch, disregarding the fact that fieldsets have already been added, and this is what my problem actually is. I also have a function (not shown here just to keep the question clear and as short as possible) that asigns new IDs to the cloned fieldset to prevent duplicate IDs and which works without a hitch.

I am convinced that I am doing something wrong, but I have been banging my head against a wall with this for two days now, trying to find what it is with no luck whatsoever so, any help would be more than appreciated !

Thanks in advance !

解决方案

I don't like the solution of Nate B.

  • it needs an additional container element
  • recreates everything, thus loosing data already entered
  • creates a maintenance problem: html markup of the fieldset is duplicated (once in HTML, once as string for append)
  • creates invalid id's for the fieldsets (id's can't start with a number)

This does what you want and similar to what you did. Keeps only the ids in a data attribute on the original element (instead of keeping the whole clone object which could use massive amounts of memory). Keeps all values already entered. Doesn't recreate everything if you change from e.g. 3 to 5. Instead only generates two new fieldsets. Removes them in reverse order they where created.

jQuery.fn.fieldsManage = function (number) {
    var ele = $(this);
    var clones = ele.data("clones");
    clones = clones ? clones : new Array(ele.attr("id"));
    if (clones.length < number) {
        var clone;
        while(clones.length < number) {
            clone = ele.clone(true);
            var id = clones[0]+clones.length;
            clone.attr("id", id);
            $("#"+clones[clones.length-1]).after(clone);
            clones.push(id);
        }
    } else {
        while(clones.length > number) {
            $("#"+clones.pop()).remove();
        }
    }
    ele.data("clones", clones);
}

$(document).ready(function() {
    $("#itemCount").change(function() {
        $("#item_dup_1").fieldsManage(this.value);
    });
});

这篇关于使用jQuery根据下拉框值动态添加表单域(或fieldsets)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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