使用 JavaScript 在<选择>中查找选定的<选项>

Finding the selected <option> in a <select> using JavaScript

本文关键字:选项 查找 选择 JavaScript 使用      更新时间:2023-09-26

我想知道什么时候有人点击了特定的选择选项。 它适用于搜索表单,我希望用户能够在日期之间搜索,因此,如果他们选择在日期之间搜索的选项,则它将显示第二个日期搜索字段。我正在使用引导日期选择器进行日期输入

这是我的HTML示例:

<select name="select_menu" id="select_field">
    <option value="select_one">Please Select One</option>
    <option value="search_between_dates">Search Between Two Dates</option>
</select>
<input type="text" name="date" id="dpd1" class="dpd1">
<div id="select_feed"></div>

示例 PHP:

if(isset($_GET['filter'])) {
    $filter = mysql_real_escape_string($_GET['filter']);
    if($filter == 'search_between_dates') {
        $date1 = $_GET['date'];
        $date2 = $_GET['date2'];
        $query = "SELECT * FROM table WHERE date BETWEEN '".$date1."' AND '".$date2."';
        // So on and so forth
    } elseif($filter == '') {
        //So on and so forth
    }
} else {}

您可以使用javascript获取选定的选项索引/值,然后从那里进行处理。

selectBox = document.getElementById("select_field");
currentIndex = selectBox.selectedIndex;
currentValue = selectBox[currentIndex].value;
//Continue processing as you need

根据您的需要,这将为您提供用户当前选择的选项的索引值以及"值"属性的内容。

附带说明一下,您的代码容易受到SQL注入攻击,如果这是一个新项目,则应考虑使用MySQLi库而不是常规的mysql_*函数集。 它们不再受支持,我相信它们也已被弃用。

像这样更改您的 HTML:

<select name="select_menu" id="select_field">
    <option value="select_one">Please Select One</option>
    <option value="search_between_dates">Search Between Two Dates</option>
</select>
<input type="text" name="date" id="dpd1" class="dpd1">
<input type="text" name="date2" id="dpd2" class="hidden">
<div id="select_feed"></div>

然后你可以使用一些jquery来显示第二个输入:

$( document ).ready( function() {
  $('#select_field').change(function() {
    if ($('#select_field').val() == "search_between_dates") {
      $('#dpd2').show();
    }
  });
});

注意:我实际上没有测试代码,因此那里可能隐藏了一个微妙的语法错误。