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
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>

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.