Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SOLVED: jQuery adding dynamic form elements

Jeb675:

I want to create two dynamic form elements so that when the user clicks "add another question" they get a new question Field and a answer field and the html is manipulated to "Q2", "A2" etc. I was able to create a dynamic form Element to add a new question Input based on this blog but can't manage to add an answer field too.


//disable delete question
$(document).ready(function() {
$('#btnDel').prop('disabled', 'disabled');
});

//add question
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 2); // the numeric ID of the new Q input field being added
var newNumA = new Number(num + 3); // the numeric ID of the new A input field being added

// Question Input

// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#qInput' + num).clone().prop('id', 'qInput' + newNum);

// manipulate the name/id/html of the span inside the new element
newElem.children(':first').prop('id', 'spanQ' + newNum).html("Q" + newNum);

// manipulate the name/id/val values of the input inside the new element
newElem.children().eq(1).prop('id', 'question' + newNum).prop('name', 'question' + newNum).val("");


//Answer Input

// create the new element via clone(), and manipulate it's ID using newNumA value
var newElemA = $('#aInput' + num).clone().prop('id', 'aInput' + newNumA);

// manipulate the name/id/html of the span inside the new element
newElemA.children(':first').prop('id', 'spanA' + newNumA).html("A" + newNumA);

// manipulate the name/id/val values of the input inside the new element
newElemA.children().eq(1).prop('id', 'answer' + newNumA).prop('name', 'answer' + newNumA).val("");


// insert the new element after the last "duplicatable" input field
$('#aInput' + num).after(newElem, newElemA);

// enable the "remove" button
$('#btnDel').prop('disabled', '');

// business rule: you can only add 19 questions
if (newNum == 19)
$('#btnAdd').prop('disabled', 'disabled');
});






Q1



A1

















Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots


This post first appeared on Stack Solved, please read the originial post: here

Share the post

SOLVED: jQuery adding dynamic form elements

×

Subscribe to Stack Solved

Get updates delivered right to your inbox!

Thank you for your subscription

×