nhoyti
nhoyti

Reputation: 1997

How to change the "accept" value of input file on radio button click

The scenario is that I need to select which type of file I need to upload. After I have selected a file type (e.g XML) the file upload dialog box will open and filter the types of the file selected to XML only. Same goes to the other options in the radio buttons. I need to get the values selected in the radio button to be placed on the "accept" property of the file upload. Is there a way to achieve this?

HTML code here

<input type="radio" class="selectfileclass" name="file" id="xml" value="xml" />XML<br />
<input type="radio" class="selectfileclass" name="file" id="html" value="html" />HTML<br />
<input type="radio" class="selectfileclass" name="file" id="json" value="json" />JSON<br />

<span class="btn btn-default btn-file btn-primary">Browse<input type="file" id="ImportFile" accept=".xml" data-bind="event: { change: $root.Browse }"></span>

Upvotes: 6

Views: 8707

Answers (2)

Use a .change() event on the radio buttons, and set the value of the input after. To set the value of the "accept" use .attr() like .attr("accept", "." + $(this).val())

$('.selectfileclass').change(function() {
  $('#ImportFile').attr("accept", "." + $(this).val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" class="selectfileclass" name="file" id="xml" value="xml" />XML<br />
<input type="radio" class="selectfileclass" name="file" id="html" value="html" />HTML<br />
<input type="radio" class="selectfileclass" name="file" id="json" value="json" />JSON<br />

<span class="btn btn-default btn-file btn-primary">Browse<input type="file" id="ImportFile" accept=".xml" data-bind="event: { change: $root.Browse }"></span>

If you want to select multiple parameters, you would have to use a checkbox and not radio.

$('.selectfileclass').click(function() {
  var s = $('.selectfileclass:checked').map(function() {
    return "." + $(this).val()
  }).get().join(",")
  console.log(s)
  $('#ImportFile').attr("accept", "." + s)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="selectfileclass" name="file" id="xml" value="xml" />XML<br />
<input type="checkbox" class="selectfileclass" name="file" id="html" value="html" />HTML<br />
<input type="checkbox" class="selectfileclass" name="file" id="json" value="json" />JSON<br />

<span class="btn btn-default btn-file btn-primary">Browse<input type="file" id="ImportFile" accept=".xml" data-bind="event: { change: $root.Browse }"></span>

Upvotes: 13

Gohel Dhaval
Gohel Dhaval

Reputation: 830

You can Try live event for that For E.g

$('input[type="radio"]').on('change',function() {
  $('#ImportFile').attr("accept", "." + $(this).val())
  console.log($(this).val());
});

Upvotes: 0

Related Questions