0

Here is my html code:

<form method="POST" action="" class="form1">
    <input type="submit" name="submit" value="Generate"><br>
    <h3>Questions</h3><button class="new_btn">Add New</button><br>
    <div class="add_ques">
        <span>Question1</span><textarea name="ques1" id="ques1"></textarea><br>
        Option1<select class="option" name="opt1" id="opt1">
            <option value="1">1</option>
            <option value="2">2</option>
        </select><br>
    </div>
</form>

When add new button is clicked another set of Question and Option fields will be appended to the end. Name and id of that fields will be automatically incremented. For example: name of next question will be ques2. I need to get the values of all the question using jquery. I have tried following code:

jQuery(".form1").submit(function(){
        for (var i = 1; i <= counter; i++) {
            qus[i] = jQuery('#ques'+i).val();
        }
        alert(qus);
}); 

No alert is displayed. And error is shown in the console on line "qus[i] = jQuery('.ques'+i).val();" . Help me to find error in my code

Sandra
  • 418
  • 1
  • 5
  • 14
  • What's `counter` in `var i = 1; i <= counter; i++`? – j08691 Dec 19 '17 at 14:53
  • how's you are getting `counter` ? – Alive to die - Anant Dec 19 '17 at 14:53
  • i get counter value during the "Add New" button click. Counter value is set to the number of times we click Add New button. And i have checked whether counter value is set and its working correctly. – Sandra Dec 19 '17 at 14:55
  • I would read up on e.preventdefault. You'll need to it prevent the form from reloading the page. Link: https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false/1357151#1357151 – SteveB Dec 19 '17 at 14:58
  • 1,`id` need to be unique per element and i smell that `id="ques1"` is repleated for each element.2. since it's `id` so in jQuery code `jQuery('.ques'+i)` need to be `jQuery('#ques'+i)`. Also show your add more button code . so that we can know that actually `ques1,ques2,ques3...` are generated properly or not?4, `preventDefault()` needed too – Alive to die - Anant Dec 19 '17 at 14:58
  • Even after giving e.preventdefault the page get reloaded – Sandra Dec 19 '17 at 14:59
  • @Sandra read my previous comment – Alive to die - Anant Dec 19 '17 at 15:02
  • @Sandra why don't you try append() to add new input fields in form, it will automatically result in all form fields values passed when you submit form. – Manish Verma Dec 19 '17 at 15:06
  • @Alive to Die--Anant Singh name is generated properly and id's are also unique. – Sandra Dec 19 '17 at 17:19

1 Answers1

1

I have found the solution

jQuery(".form1").submit(function(e){

                    qus =[];

                    for (var i = 1; i <= counter; i++) {
                        qus.push(jQuery('#ques'+i).val());

                    }

            });
Sandra
  • 418
  • 1
  • 5
  • 14