Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to append input type file

Tags:

html

jquery

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');

    });
like image 851
user8663822 Avatar asked Dec 21 '25 03:12

user8663822


2 Answers

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.

like image 76
Rory McCrossan Avatar answered Dec 22 '25 15:12

Rory McCrossan


$(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>
like image 31
Farhad Bagherlo Avatar answered Dec 22 '25 15:12

Farhad Bagherlo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!