1

I am new to php and wanted to now, how can I add text fields at runtime. I have created a php page with a simple dropdown list in it.The dropdown list has numbers 1,2,3 and so on. What I want to do is that whenever a user selects a number from dropdown list, the same number of text fields (along with labels) appear. Example 1 textfield for 1 (with label), 2 textfields for 2 and so on . If someone can give me any code example or a link to understand, It will be very helpful . Thanks alot :)

3
  • 3
    sounds like you want javascript not php. to do it with php the form would have to be submitted to create the textfields Commented Jul 12, 2012 at 4:25
  • @Dagon can you please give me any code example or a link to do it with javascript? thanks Commented Jul 12, 2012 at 4:26
  • I'm fond of the jquery Library jquery.com Commented Jul 12, 2012 at 4:29

3 Answers 3

2

I would use jquery, a JavaScript library as Dagon suggested. First your html:

<form>
  <input class="target" type="text" value="Field 1" />
  <select class="target">
    <option value="1" selected="selected">Option 1</option>
    <option value="2">Option 2</option>
  </select>
</form>
<div id="other">

</div>

Then your javascript (using jQuery):

$('.target').change(function() {
    $("select option:selected").each(function () {
        $('#other').append("<label>" + $(this).text() + "</label><input type='text' value='' />");
    });      
});

For your reference:

http://api.jquery.com/change/

http://api.jquery.com/append/

Sign up to request clarification or add additional context in comments.

Comments

1

You can use jQuery to help you. Use change() function ( http://api.jquery.com/change/ ) to get the drop down list value and create another jQuery function to populate the text fields.

This tutorial might help you http://charlie.griefer.com/blog/2009/09/17/jquery-dynamically-adding-form-elements/

Comments

1

Here's how you can do that:

<?php 
$num = 2; //get number input from user
for ($i = 0; $i < $num ; $i++) {
echo '<input type="text" />';
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.