Home > database >  How to change accept attribute of input type file based on select file type using javascript?
How to change accept attribute of input type file based on select file type using javascript?

Time:06-07

I have a select list like this

<select asp-for="FileTypeIndex"  id="FileTypeIndex" asp-items="Html.GetEnumSelectList<FileTypeIndex>()"></select>

<input type="file"  accept="*.*" id="productfile" name="productfile">

I want to change the accept attribute of file input according to the selected FileTypeIndex by JQuery

  $('#FileTypeIndex').on('change',function() {
         var filytypeIndex=$('#FileTypeIndex').val();
        
         switch(filytypeIndex) {              
          case 1:
            $('#productfile').attr("accept", ".pdf");
            break;
          case 2:
          case 5:
            $('#productfile').attr("accept", ".mp4,.avi");
            break;
          case 3:
            $('#productfile').attr("accept", ".mp3");
            break;
            case 4:
            $('#productfile').attr("accept", ".jpg");
            break;
          default:
        }
  });

But it is always ".", and it won't change

CodePudding user response:

You just need to change the datatype of filytypeIndex variable to number using Number() function of javascript.

Because in switch case gives 1,2,3 ... it is numbers

Your final code like below

$('#FileTypeIndex').on('change', function () {
    var filytypeIndex = Number($('#FileTypeIndex').val());
    switch (filytypeIndex) {
        case 1:
            $('#productfile').attr("accept", ".pdf");
            break;
        case 2:
        case 5:
            $('#productfile').attr("accept", ".mp4,.avi");
            break;
        case 3:
            $('#productfile').attr("accept", ".mp3");
            break;
        case 4:
            $('#productfile').attr("accept", ".jpg");
            break;
        default:
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select asp-for="FileTypeIndex"  id="FileTypeIndex" asp-items="Html.GetEnumSelectList<FileTypeIndex>()">
      <option value="1">1</option>  
      <option value="2">2</option>  
      <option value="3">3</option>  
      <option value="4">4</option>  
      <option value="5">5</option>  
</select>

<input type="file"  accept="*.*" id="productfile" name="productfile">

  • Related