使用相同的输入文件标记获取元素名称

时间:2016-01-11 07:28:27

标签: javascript jquery html

我在jQuery代码中遇到问题。我有两个不同名称的HTML输入文件代码。如何在jQuery中获取第二个输入文件名

这是我的HTML代码:

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

这是我的jQuery代码:

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

如何获得名称 photo_b ,我的jquery代码只需获取 photo_a 名称。

请帮我解决这个问题:)

3 个答案:

答案 0 :(得分:2)

使用jquery eq在选择中按索引获取元素,选择提供两个输入,eq(1)按索引选择第二个。此外,根据请求,使用change事件侦听器,当您选择要上载的图像时,您将获得所选的文件按钮名称:

&#13;
&#13;
$(document).ready(function(){


  $('input[type=file]').change(function(){
    
    
    alert($(this).attr("name"));
          
  });
  
$("#secFileName").html($('input[type=file]').eq(1).attr('name'));

});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

为什么不直接使用js函数?

document.getElementsByName("photo_b");

答案 2 :(得分:0)

你必须做

//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)" />

相关问题