Home > database >  upload file types according to radio button selections
upload file types according to radio button selections

Time:10-12

I am developing a html page, in which I am using two radio buttons say A and B,(A will be checked as default)

required solutiuon : when a user selects on A button

they should allowed to upload only .csv and .txt files, if they select another file, it should throw a message

Also, if they select radio button 'B' , they should allowed only to upload .config files

I have tried this much far :

   <div class="form-group">

     <label class="col col-md-2 control-label"><span class="widget-icon">
        <i class="fa fa-file txt-color-black"></i>Type of File </label>
       <div class="col-md-2">
       <label class="radio-inline">
      <input type="radio" class="selectfileclass" name="file" id="file_a" value="csv,txt" 
      checked/>File_A<br />

     </label>
    <label class="radio-inline">
      <input type="radio" class="selectfileclass" name="file" id="config" value="config" 
       />Config<br />
     </label>
    
    
  <br>
  <br>
    </div>
  
    </div>
  </form>

 <span class="btn"><input type="file" class="selectfileclass" id="ImportFile" 
 accept=".csv,.txt" data-bind="event: { change: $root.Browse }"/></span>
 <script>
$('.selectfileclass').change(function() {
$('#ImportFile').attr("accept", "."   $(this).val())
})
</script>

still stuck, where I am missing,

any help will be appreciated!

Thanks

CodePudding user response:

When you put a dot before "csv,txt" it becomes ".csv,txt" which is not a comma separated list of unique file type specifiers.

Perhaps the simplest solution is to put the file specifier list in radio button attribute values, and don't process them further when changing the accept attribute value of the file input.

<input type="radio" class="selectfileclass" name="file" id="file_a" value=".csv,.txt" checked>
 ...
<input type="radio" class="selectfileclass" name="file" id="config" value=".config">
 ...
 ...
    $('#ImportFile').attr("accept", $(this).val())

A possible enhancement to ensure the uploaded radio button file value matches the type of the files selected would be to clear the file input value when the radio buttons are changed:

   $('#ImportFile').val(""); // before setting
   $('#ImportFile').attr("accept", $(this).val())
  • Related