当值'其他'时,如何显示HTML输入字段?用PHP选择

时间:2016-11-14 02:55:50

标签: php html

我想弄清楚当从下拉菜单中选择其他的值时,如何显示html 输入字段。现在,下拉列表的值来自MySQL数据库查询的结果,这可以工作,但我似乎无法弄清楚当我选择其他选项时如何获得输入。

$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

2 个答案:

答案 0 :(得分:3)

使用javascript,如下例所示。我们可以使用样式属性添加input字段并默认隐藏它:     <input name='otherInput' id='otherInput' type="text" style="display: none" />

&#13;
&#13;
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';
  }
}
&#13;
<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" />
&#13;
&#13;
&#13;

有第三方库,如jQuery,AngularJS,PrototypeJS等,可以通过添加DOM操作的快捷方法来使代码更简单(尽管你应该阅读this post)。例如,使用jQuery,使用.on()(用于事件处理程序绑定),.show().hide()用于输入显示切换等:

&#13;
&#13;
var otherInput;
var serviceTypeInput = $('#service_type');
serviceTypeInput.on('change', function() {
  otherInput = $('#otherInput');
  if (serviceTypeInput.val() == "Other") {
    otherInput.show();
  } else {
    otherInput.hide();
  }
});
&#13;
<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" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$(function() {
  $('#sample').change(function() {
    var val = this.value; // get the value of the select.
    if (val == 'other') { // if the value is equal to "other" then append input below the select
      $('html').append('<input type="text" id="inputOther"/>');
    } else { // else then remove the input
      $('#inputOther').remove();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sample">
  <option value="test1">test1</option>
  <option value="test2">test2</option>
  <option value="test3">test3</option>
  <option value="other">other</option>
</select>