thatdamsasqotch
thatdamsasqotch

Reputation: 1

Javascript show/hide text field input if 'Other' selected in multiple select input

I'm afraid I'm stuck and I was hoping for a some community wisdom.

I am building an HTML form which submits data to a SQL database. One of the form fields is a multiple select input field where users can select the type of operation being performed. The array then gets exported to a SQL field as comma-separated values.

The issue I'm having is that I also want users to be able to enter a custom operation type if it is not included in the provided list. Ideally this would involve selecting 'Other' in the multiple select and having a new text input field appear.

So far I can only make the text input field appear if the user has selected 'Other' and nothing else. Can I have the field appear if the user has selected multiple items, one of which is 'Other'?

Many thanks

function showfield(episode_procedure){
          if(episode_procedure=='Other')document.getElementById('otherprocedure').innerHTML='Other: <input type="text" name="episode_otherprocedure" style="width: 450px;"/>';
          else document.getElementById('otherprocedure').innerHTML='';
        }
   
<select multiple="multiple" data-placeholder="Click to select..." size="7" name="episode_procedure[]" style="width: 450px;" onchange="showfield(this.options[this.selectedIndex].value)"></p>
        <option value="anterior resection">anterior resection</option>
        <option value="appendicectomy">appendicectomy</option>
        <option value="Other">Other</option></select>
        
        <div id="otherprocedure"></div>

Upvotes: 0

Views: 893

Answers (1)

Dekel
Dekel

Reputation: 62596

Using jQuery it's very easy to get all the values in a multiple select tag:

$(select).val()

Now you only need to check if the 'Other' exists inside:

$(select).val().indexOf('Other') > -1

$('#s1').on('change', function() {
  if ($(this).val().indexOf('Other') > -1) {
    $('#otherprocedure').html('Other: <input type="text" name="episode_otherprocedure" style="width: 450px;"/>')
  } else {
    $('#otherprocedure').html('');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s1" multiple="multiple" data-placeholder="Click to select..." size="7" name="episode_procedure[]" style="width: 450px;">
<option value="anterior resection">anterior resection</option>
<option value="appendicectomy">appendicectomy</option>
<option value="Other">Other</option></select>

<div id="otherprocedure"></div>

Upvotes: 1

Related Questions