3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

(HTML5)datalist JQueryでお手軽取得(value&label)

Last updated at Posted at 2019-05-25

HTML5から使えるdatalistをいまさらながら使ってみる

##HTML

<input type="search" name="sample" autocomplete="on" list="list">
<datalist id="list">
    <option value="apple" label="りんご">
    <option value="lemon" label="れもん">
    <option value="banana" label="ばなな">
</datalist>

autocompleteはinput要素の入力候補を簡単に表示できます。
list属性とdatalistのid属性は同じもの指定します。

こんな感じの見た目になると思います。
Screenshot_1.png

##Jquery/Js

<script>
    $('input[name=sample]').on('change', function () {
        console.log($(this).val()); //value値
        console.log($("#list option[value='" + $(this).val() + "']").prop('label')) //label値
    });
</script>

value値は、val関数を使って取得できます。
labelはdatalist内に記述されているため、今回は、そのvalue値を持っているoptionのlabelを取得という形にしております。

console.logでこのようにでれば、完了です。(apple-リンゴ選択)
Screenshot_2.png

3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?