html - Create new form fields on click using javascript -
i have form asks general information (i called gen-info) , fieldset inside form in ask other information.
what i'm trying create new fieldset asking same other info , rename it, know how create copy of whole form (which asks general info too).
by i'm creating button this:
<button type="button" id="btnaddform" onclick="cloneform('gen-info');">add other info</button>
and i'm using javascript function:
function cloneform(formname) { var formcount = document.forms.length; var oform = document.forms[formname]; var clone = oform.clonenode(true); clone.name += "new form " + formcount; document.body.appendchild(clone); }
as can see, duplicate whole form, want duplicate part says "other information 1" , rename "other information 2" when click , add 1 name every time create new one. difference i'm duplicating whole form every time, , want duplicate fieldset.
thank much!
here how can these kind of operations jquery, ive commented each line can follow logic. html altered (you had no closing </fieldset>
)
//on startup $(function() { //add click event-handler button $("#btnaddform").click(function() { $clone = $("fieldset").last().clone() //clone last fieldset $number = $clone.find("span") //get element number $number.html(parseint($number.html()) + 1) //add 1 number $("fieldset").last().after($clone) //insert new clone }) })
and here entire thing, note jquery included script in dropdown left. https://jsfiddle.net/tx839gf3/4/
edit, heres 1 gives new names, theres new row in start, , 3 rows iterating on input-elements, , naming them:
$(function() { var n = 4 //start naming elements number $("#btnaddform").click(function() { $clone = $("fieldset").last().clone() //clone last fieldset $number = $clone.find("span") //get element number $number.html(parseint($number.html()) + 1) //calc , set new number //loop input fields in copied group $clone.find("input").each(function() { $(this).attr("name", "other-info-" + n++) //set new name-number (and iterate it) }) $("fieldset").last().after($clone) //insert new clone }) })
Comments
Post a Comment