1
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 3 years have passed since last update.

HTML datalistタグでvalueと違う値をsubmitしたい

Posted at

datalistでvalueとは違う値をsubmitしたい

datalistタグはselectタグとはちがって、valueが表示されてしまう。
optionの中に書いても、valueの方が目立って表示されるし不便……
表示自体は「name1」などのテキストにしたい。でもpostするのは「id1」とか別の値が良いのよな~
そんな時は、jsごりごりして、post用のhiddenなinputを用意すれば簡単。

やればよいこと

  • js(今回はjquery)でごにょごにょする。
  • data属性を使えば良い。
  • submitする際は、hiddenなinputでpostすればよい。

HTML

index.html
<label for="stage"></label>
<input id="stage_input" list="search_stages" class="" name="" value="$default_value">
<datalist id="search_stages">
    <option value="name1" data-id="id1"></option>
    <option value="name2" data-id="id2"></option>
    <option value="name3" data-id="id3"></option>
</datalist>
<input id="stage" type="hidden" name="stage" value="">

<script src="jsfile.js"></script>

jQuery

jsfile.js

let id = null;
// datalistのdata-id属性の値の取得
$('#stage_input').on('change', function () {
  id = $("#search_stages option[value='" + $(this).val() + "']").data('id');
});
// submit
$('#sub_btn').click(function () {
  $('#stage').val(id);
  $('#search_form').submit();
});
1
1
0

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
1
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?