Reputation: 1212
I am making a quiz website and at the edit screen of a {id} quiz can I edit + add questions (and answers)
Now I have a form, which I want to "copy" using JavaScript so it gets dynamic, ofcourse the Question number should be 2, 3, 4 and so forth after clicking on "Add Question"
This is what I had before, but I think there is a more efficient way to sort of copy the form instead of making a complete new one.
But I'm kind off stuck with how to do it..
HTML
{{ Form::open(array('url'=>'quizzes/edit', 'id' => 'quiz')) }}
{{ Form::button('Add Question', array('onclick' => 'addQuestion()', 'id' => 'questionadd', 'value' => 'Add new question')) }}
{{ Form::submit('Edit Quiz', array('id' => 'quizsubmit')) }}
<p id="questiontitle">Question 1</p>
{{ Form::text('', null, array('placeholder' => 'Question 1', 'size' => '40', 'id' => 'questions', 'onfocus' => 'showAnswers(this)')) }} <br>
{{ Form::text('', null, array('placeholder' => 'Good Answer', 'size' => '30', 'id' => 'answers')) }}
{{ Form::text('', null, array('placeholder' => 'False Answer', 'size' => '30', 'id' => 'answers')) }}
{{ Form::text('', null, array('placeholder' => 'False Answer', 'size' => '30', 'id' => 'answers')) }}
{{ Form::close() }}
JavaScript
var qlimit = 10; // Max questions
var qcount = 1; // There are 4 questions already
function addQuestion()
{
// Get the quiz form element
var quiz = document.getElementById('quiz');
// Good to do error checking, make sure we managed to get something
if (quiz) {
if (qcount < qlimit) {
// Create a new <p> element
var newQ = document.createElement('p');
newQ.innerHTML = 'Question ' + (qcount + 1);
// Create the new text box
var newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'questions[]'
var newQ = document.createElement('p');
newQ.innerHTML = 'Question ' + (qcount + 1);
// Error checking
if (newInput && newQ) {
// Add the new elements to the form
quiz.appendChild(newQ);
quiz.appendChild(newInput);
// Increment the count
qcount++;
}
}
// Error message when maximum amount of questions is reached
else {
alert('The maximum amount of questions is ' + qcount);
}
}
}
Upvotes: 1
Views: 534
Reputation: 21
var quizForm = document.getElementByID('quiz').outerHTML;
This will copy your quiz-form. then if you want to change values (and i think that is what you want) you need to give all elements an ID and align the new values to the elements. Like:
document.getElementByID('questions').value = 'new value';
Does your three Answers in the Example have the same ID? IDs must be unique.
Upvotes: 1