Vlad Vlad - 21 days ago 7
HTML Question

How to have an HTML input field appear when the value 'other' is selected with PHP

What I am trying to figure out is how to have an html input field appear when the value of other is selected from a dropdown menu. Right now the values for the dropdown list are coming from the results of a MySQL DB query, which works, but I can not seem to figure out how to get an input to appear when I select the other option.

$query = mysql_query("SELECT type FROM Dropdown_Service_Type"); // Run your query

echo '<select name="service_type">'; // Open your drop down box

echo '<option value="NULL"></option>';
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo '<option value="Other">Other</option>';
echo '</select>';// Close your drop down box

Answer

Use javascript, like in the example below. We can add an input field and have it hidden by default, using the style attribute: <input name='otherInput' id='otherInput' type="text" style="display: none" />

var otherInput;
function checkOptions(select) {
  otherInput = document.getElementById('otherInput');
  if (select.options[select.selectedIndex].value == "Other") {
    otherInput.style.display = 'block';
    
  }
  else {
    otherInput.style.display = 'none';
  }
}
<select onchange="checkOptions(this)" name="service_type" id="service_type">
  <option value="NULL"></option>
  <option value="43">43</option>
  <!-- other options from your database query results displayed here -->
  <option value="Other">Other</option>
</select>
<!-- the style attribute here has display none initially, so it will be hidden by default -->
<input name='otherInput' id='otherInput' type="text" style="display: none" />

With jQuery, it gets simpler, using .on() (for the event handler binding), .show() and .hide() for the input display toggling, etc:

var otherInput;
var serviceTypeInput = $('#service_type');
serviceTypeInput.on('change', function() {
  otherInput = $('#otherInput');
  if (serviceTypeInput.val() == "Other") {
    otherInput.show();
  } else {
    otherInput.hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="service_type" id="service_type">
  <option value="NULL"></option>
  <option value="43">43</option>
  <option value="Other">Other</option>
</select>
<input name='otherInput' id='otherInput' type="text" style="display: none" />

Comments