简体   繁体   中英

using ajax to get more form fields

I have a page that has a form on it:

index.php

 <script>
var userId = $('#userId').val();
 $('#moreFields').click (function()
 {
                    $.ajax(
                    {  
                            type: "POST",  
                            url: "addToForm.php",
                            data: "userId="+userId,
                            success: function(result)
                            { 
                              $('#dialog').html(result);
                            }
                    });
  });
  </script>


  <form id='userInfo' name='userInfo' method='POST' action='#'>
   <input type='text' name='userName' id='userName'>
   <select name='optionChoice' id='optionChoice'>
       <option value='1'>1</option>
       <option value='2'>2</option>
       <option value='3'>3</option>
       <option value='4'>4</option>
   </select>
 <input type='button' id='moreFields' name='moreFields' value='Add Fields'>

  <div id='dialog'></div>

addtoForm.php

 <input type='text' name='job' id='job'>
 <input type='text' name='salary' id='salary'>

based on the option the user selects. I want to add additional fields. I do this by sending an ajax call to addtoForm.php that has the form fields in it. These form fields show up in a dialog. My question is, will these form fields be attributed to the same form id as the form on index.php page? Will the form with id userInfo have userName,optionChoice,job, and salary as elements in the form?

Your current code wont add the additional fields to the form, it just adds them to the div#dialog which is outside the form.

To add the fields to the form you could use jquery's berfore() method:

$('#moreFields').before(result);

However, as your addtoform.php doe not do any calculation at all, and simple returns html, the whole ajax request is pointless. You may as well just add the fields with js:

$('#moreFields').click (function(){
        $(this).before('<input type=\'text\' name=\'job\' id=\'job\'> <input type=\'text\' name=\'salary\' id=\'salary\'>');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM