Jump to content

Dynamic input text field(s)


ivytony

Recommended Posts

I'm trying to make a PHP script with AJAX that allows users to enter the number of rebates when they submit an entry. On the same submission page, when they enter the number of rebates (say 3), 3 text fields will be populated underneath the number fields. Someone helped me make this PHP script:

 

<html>
<head>
</head>
<body>
Number of rebates?
<br>
<form method="post">
<input type="text" name="numrebates">
<br>
<input type="submit"">
</form>
<br>
<div id="rebatesdiv">
<?php
$numrebates=$_POST['numrebates'];
$fieldnum="1";

while ($numrebates >= 1) {
$numrebates--;

print("<br>
<input type=\"text\" name=\"field$fieldnum\">
<br>");

$fieldnum++;
}
?>
</div>
</body>
</html>

 

But it requires users to click 'submit', I really want the user to stay on the same page without losing other already entered texts. I am wondering if someone here can help create the ajax part.

 

Thanks!!!

Link to comment
https://forums.phpfreaks.com/topic/92349-dynamic-input-text-fields/
Share on other sites

I would recommend something like this, which doesn't use PHP or AJAX, just some javascript. When posted to PHP, you can access the rebates with $_POST['rebates'] which will be an array.

 

<html>
  <head>
  </head>
  <body>
    <script type="text/javascript">
      function addRebate ( ) {
        document.getElementById('rebatesList').innerHTML += '<li><input type="text" name="rebates[]"></li>';
      }
    </script>
    <form method="post">
      <div>
        REBATES:
        <ul id="rebatesList"></ul>
        <input type="button" value="Add Rebate" onclick="addRebate();" />
      </div>
    </form>
  </body>
</html>

very nice!

 

then the name of input text field will be like rebates1, rebates2, ....? I need to know the names to get their value, right?

 

one problem is: after I add one rebate to the first input field, I click the button 'add rebate'. My first rebate is totally lost. How to fix this problem?

 

thanks!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.