简体   繁体   中英

Get Elements Name with the same Input File tag

I have a problem in jQuery code. I have two HTML input file code with different name. How do I get the second input file name in jQuery

Here is my HTML Code :

<input type="file" name="photo_a"   />
<input type="file" name="photo_b" />

And Here is my jQuery Code :

var nameElement = $('input[type=file]').attr('name');
alert(nameElement);

How do i get the name photo_b , my jquery code just get the photo_a name.

Please help me solve this :)

Use jquery eq to get the element by index in the selection, the selection gives both inputs, eq(1) selects the second one by index. Also, as per requested, use change event listener, when you select an image to upload, you get the file button name you selected:

 $(document).ready(function(){ $('input[type=file]').change(function(){ alert($(this).attr("name")); }); $("#secFileName").html($('input[type=file]').eq(1).attr('name')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" name="photo_a" /> <input type="file" name="photo_b" /> <br /><br /> Second File Name <div id="secFileName"></div> 

为什么不简单地仅使用js函数呢?

document.getElementsByName("photo_b");

You have to do

 //it gets current changed file name function getName(thisObj){ alert($(thisObj).attr("name")); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" name="photo_a" onchange="getName(this)" /> <input type="file" name="photo_b" onchange="getName(this)" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM