C:blanc
Published
July 15 2022
Blog JavaScript

Text box that can also be a pull-down menu

  • このエントリーをはてなブックマークに追加

Introduction.

Sometimes you use pull-downs and sometimes you want to enter values other than the default, right?
So, I created a text box that has both functions.
This time, I would like to do it with jQuery and jQuery UI.
In addition, I will add Autocomplete.

html

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">

<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.min.css" />
<link rel="stylesheet" href="./style.css" />

</head>
<body>

<input type="text" name="fruits" id="textbox" placeholder="くだもの" />

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js" integrity="sha256-lSjKY0/srUM9BE3dPm+c4fBo1dky2v27Gdjm2uoZaL0=" crossorigin="anonymous"></script>
<script src="./script.js"></script>

</body>
</html>

CSS

The absence of CSS has no particular effect on the function itself.
style.css
input[type="text"] {
    box-sizing: border-box;
    width: 10em;
    margin: 0;
    padding: 0.5em;
    border: none;
    background-color: #fffbea;
    text-align: left;
    font-size: 16px;
    line-height: 1;
}

input[type="text"]:focus {
    background-color: #f8ffbe;
}

Javascript

It works with autocomplete only, not pull-down menus.
In that case, you can call the DB data with ajax and have it autocomplete.
script.js
$('#textbox').autocomplete({
    minLength : 0,
    delay : 0,
    source: function(request, response) {
        response(
            $.grep(['りんご', 'みかん', 'バナナ', 'ぶどう', 'パイナップル', 'パイナップルジュース'], function(value) {
                return value.indexOf(request.term) === 0;
            })
        );
    },
    select : function(event, ui) {
        $(this).val(ui.item.name)
    }
}).focus(function() {
    $(this).autocomplete('search', '')
});

DEMO

https://blog.c-blanc.com/demo/blog/6/

In addition to text boxes, pull-down menus also work.
The pull-down menu also has an autocomplete function, so for example, typing "pa" or "pina" will list "pineapple" and "pineapple juice".
It is like a three-in-one machine.

At the end.

jQuery is still in use, right?
'What, you're still using it?' And?
However, jQuery UI is no longer under development.
We have to think of a replacement. (What would be better?).
I use datepicker and others a lot, so it's hard.
I wonder what will happen in the future now that HTML5 has been discontinued.

PROFILE

C:blanc
I am a freelance programmer.
  • COMMENT

    Submitted. Comments will appear after approval.
  • あと150more characters