2016-04-22 80 views
1

我有一個動態頁面,可以有很多input[type="file"]字段。選擇文件後,我需要更改每個輸入的標籤。更改多個輸入的標籤文本

所以,對於每一個輸入,如果有:

  • 空:文本= 「上載」;
  • 選定的文件:文本=文件的名稱。

這裏是HTML的一個示例:

<label for="upload-qm1"> 
    <span class="button">upload</span> 
    <input id="upload-qm1" type="file" accept=".pdf, .doc"> 
</label> 

我知道如何爲一個單一的input做到這一點,使用此代碼:

$('label[for="upload-qm1"] span').text($(this).val()); 

不過,我不知道如何許多input字段,我將在我的頁面上。我試過這樣的事情:

$(this).parent('label').find('span').text($(this).val()); 

但不幸的是它不起作用。任何關於如何獲得更改所有input字段的方法的幫助?

回答

4

您可以使用DOM遍歷來查找input已更改的相關span。試試這個:

$('input:file').change(function() { 
    $(this).prev('span').text($(this).val()); 
}) 

Working example

0

的大部分代碼,你試過IST corret。 問題是你已經爲parent()函數設置了一個參數。

嘗試這樣: $(this).parent('label').find('span').text($(this).val());

另外,還要確保$(this)是輸入字段沒有標籤本身, 如果您單擊標籤$(this)上是標籤。

0

$('input[type="file"]').on('change', function() { 
 
     id = $(this).attr('id'); 
 
      console.log("change event") 
 
     var file = $('#'+id).val().split('\\').pop(); 
 
     if(file!='') { 
 
      $('label[for="'+id+'"] span').text(file) 
 
     } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label for="upload-qm1"> 
 
    <span class="button">upload</span> 
 
    <input id="upload-qm1" type="file" accept=".pdf, .doc"> 
 
</label>