Using jQuery to dynamically add form fields (or fieldsets) based on a dropdown box 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 ... ... 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 `
`. 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 !

以上就是Using jQuery to dynamically add form fields (or fieldsets) based on a dropdown box value的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » jQuery 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准