drf21989
2015-04-28 07:27
浏览 32

根据输入jquery中键入文本的第一个字母自动选择下拉列表

Hello I tried to search something equivalent without success, this is not a php based value where one drop down updates another. its a simpler version but I don't know how to proceed

Basically I have a text field like

 <input size="50" name="productname" id="product" type="text" />

 <select name="platform">
    <?php if($manufacturers) foreach($manufacturers as $each) { ?>
           <option value="<?=$each['id']?>"><?=$each[ 'manufacturerName']?></option>
    <?php } ?>
 </select>

I noticed that in about 90% of my scenario if a manufacturer name is Samsung most of its product will start with S that is the first name of the manufacturer.

In my select I have some manufacturers for example , Samsung, Alcatel, Hitachi, from a database.

In this form I am doing user will be adding new product, for example Samsung S6, as he types Samsung, I wish a jquery will set the selected option to the select list to samsung most probably based on the first matching letter.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doutidi5037 2015-04-28 08:06
    已采纳

    Try this code, then you can modified with your own creativity.

    $('#product').on('keyup', function () {
       var input_val = String($(this).val());
       var sel = $('select[name=platform]');
    
       if (input_val !== "") {
          var h = $('select option[value*=' + input_val + ']');
          if (h.length > 0) {
              h.prop('selected', true);
          } else {
              sel.val("");
          }
       } else {
          sel.val("");
       }
    
    });
    

    DEMO

    已采纳该答案
    打赏 评论
  • dongluanban3536 2015-04-28 08:00

    You might want to use jQueryUI Autocomplete.

    Below code gets necessary data first from the database and load it into the element.

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <input size="50" name="productname" id="product" type="text" />
    <?php if(mysqli_num_rows($res) > 0) { 
        while($row = mysqli_fetch_assoc($res)) {
    ?>
        <script language="javascript">
            var availableTags = [
            <?php echo "\"".$row['manufacturerName']."\","; ?>
            ];
            $("#product").autocomplete({
                source: availableTags
            });
        </script>
    <?php }
        } ?>
    
    打赏 评论

相关推荐 更多相似问题