Dilini Rajapaksha
Dilini Rajapaksha

Reputation: 2718

Add html input boxes to a div on click using jquery

I need to add input boxes to a page onclick of a button, I have written the following jquery script. It adds one input box when clicked the first time but does not repeat adding.

<script type="text/javascript">
   function addInput(){
      $('#fileinput').html('<label>Filename:</label>
                        <input type="file" name="file"  id="file" />');
   }
</script>

can some one please help me to modify the code so that it will add an input box each time the button is clicked.

Upvotes: 3

Views: 16299

Answers (4)

DMac the Destroyer
DMac the Destroyer

Reputation: 5290

try using append instead of html: http://api.jquery.com/append/

<script type="text/javascript">
 function addInput(){
  $('#fileinput').append('<label>Filename:</label>
              <input type="file" name="file"  id="file" />');
}
</script>

Upvotes: 2

Widor
Widor

Reputation: 13285

That's because you're not adding to the HTML each time, you're simply setting it to show the single input.

Upvotes: 1

kafuchau
kafuchau

Reputation: 5593

Your code currently replaces the existing HTML in your #fileInput element with the same HTML. What you probably want to use is the append() method.

   function addInput(){
      $('#fileinput').append('<label>Filename:</label>
                        <input type="file" name="file"  id="file" />');
   }

Upvotes: 2

Johnny Craig
Johnny Craig

Reputation: 5000

$('#buttonID').click(function(){
    $('#fileinput').html($('#fileinput').html()+'<label>Filename:</label>
                    <input type="file" name="file"  id="file" />');
});

or use append as others suggested

$('#buttonID').click(function(){
    $('#fileinput').append('<label>Filename:</label>
                    <input type="file" name="file"  id="file" />');
});

Upvotes: 8

Related Questions