Dynamically adding two form elements with jQuery

I am trying to create two form elements when the user clicks a button, which he can do 5 times, but I am new to jQuery so I am running into problems, here is the code: $(document).ready(function() { $('#btnAdd').click(function() { var num = $('.clonedInput').length; var numTwo = $('.clonedInputTwo').length; var newNum = new Number(num + 1); var newElem = $('#input' + num).clone().attr('id', 'input' + newNum); var newElemTwo = $('#inputTwo' + numTwo).clone().attr('id', 'input' + newNum); newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum); newElemTwo.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum); $('#input' + num).after(newElem); $('#inputTwo' + numTwo).after(newElemTwo); $('#btnDel').attr('disabled',''); if (newNum == 5) $('#btnAdd').attr('disabled','disabled'); }); $('#btnDel').click(function() { var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have $('#input' + num).remove(); // remove the last element $('#inputTwo' + num).remove(); // remove the last element // enable the "add" button $('#btnAdd').attr('disabled',''); // if only one element remains, disable the "remove" button if (num-1 == 1) $('#btnDel').attr('disabled','disabled'); }); $('#btnDel').attr('disabled','disabled'); }); The HTML:
Name:
School:
When I click the button it works once, then it just proceeds to create name elements, and no school elements!
Created jsFiddle at jsfiddle.net/e6cwd

以上就是Dynamically adding two form elements with jQuery的详细内容,更多请关注web前端其它相关文章!

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

评论 抢沙发

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

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

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏