简体   繁体   English

使用ajax获取更多表单字段

[英]using ajax to get more form fields

I have a page that has a form on it: 我的页面上有表格:

index.php 的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 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. 我通过将ajax调用发送到具有表单字段的addtoForm.php来实现。 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? 我的问题是,这些表单字段会被赋予与index.php页面上的表单相同的表单ID吗? Will the form with id userInfo have userName,optionChoice,job, and salary as elements in the form? ID为userInfo的表单是否将userName,optionChoice,job和薪水作为表单中的元素?

Your current code wont add the additional fields to the form, it just adds them to the div#dialog which is outside the form. 您当前的代码不会将其他字段添加到表单中,而只是将它们添加到表单外部的div#dialog中。

To add the fields to the form you could use jquery's berfore() method: 要将字段添加到表单,可以使用jquery的berfore()方法:

$('#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. 但是,由于您的addtoform.php根本不执行任何计算,并且简单地返回html,因此整个ajax请求毫无意义。 You may as well just add the fields with js: 您也可以只添加带有js的字段:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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