user8663822
user8663822

Reputation: 267

how to append input type file

in my html

if i change type to text it's fine but when i change it type file nothing happen when i click

<input type="file" name="pic[]" accept="image/*" >a
<input type="file" name="pic[]" accept="image/*" id="u_f">b<br>
<button type="button" class="btn btn-info" id="btn1">
 <span class="glyphicon glyphicon-plus"></span>
</button>

Here is my jquery

$(document).ready(function(){
    $("#btn1").click(function(){
        $("#u_f").append(" <input type='file' name='pic' accept='image/*' id='u_f' />b<br>.");
        // alert('hi');

    });

Upvotes: 2

Views: 8166

Answers (3)

Araston
Araston

Reputation: 101

you have to change your code according to below line

 $("#u_f").append(" <input type=\'file\' name=\'pic\' accept=\'image/*\' id=\'u_f\' />b<br>.");

Upvotes: 1

Farhad Bagherlo
Farhad Bagherlo

Reputation: 6699

$(document).ready(function(){
  $("#btn1").click(function(){
     $("#u_f").parent().append($("<input/>",{type:"file",name:"pic",accept:'image/*',id:'u_f'})).append("b<br>");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-info" id="btn1">
 <span class="glyphicon glyphicon-plus">+</span>
</button>
<hr>
<input type="file" name="pic[]" accept="image/*" >a<br>
<input type="file" name="pic[]" accept="image/*" id="u_f">b<br>

Upvotes: 3

Rory McCrossan
Rory McCrossan

Reputation: 337560

The #u_f element is an input, so you cannot append() any content to it. If you're attempting to add another file input, you can use insert(), insertAfter(), or any of the other DOM insertion methods:

$("#btn1").click(function() {
  $('<input type="file" name="pic" accept="image/*" />b<br>').insertBefore(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="pic[]" accept="image/*">a<br />
<input type="file" name="pic[]" accept="image/*">b<br />
<button type="button" class="btn btn-info" id="btn1">
 <span class="glyphicon glyphicon-plus">+</span>
</button>

Also note that I removed the id attributes as you would end up duplicating them with the added content, which would make the HTML invalid.

Upvotes: 4

Related Questions