4
0

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.

v-modelでバインドしたcheckboxのvalueに"on"という文字列が入ってしまう

Last updated at Posted at 2020-10-12

概要

checkboxの値を取得し、チェックされているか否かをBooleanでpostしたい。
しかし、なぜかvalueにBooleanではなく「on」という文字列が入ってしまう。

上記のような現象が起こった原因と解決策を自分なりに検証したので記載します。

上記の現象が起こったコード

exsample.vue
<template>
    <label
      v-for="(checkBox, key) in list"
      :key="key"
      :for="sample' + key"
    >
        <input
          :id="'sample' + key"
          v-model="checkBox.checkboxStatus"
          type="checkbox"
          name="sample[]"
          class="input"
        />
    <label>
</template>

<script>
  export default {
    data() {
      return {
        list: {
          { id: 1, checkboxStatus: false },
          { id: 2, checkboxStatus: false },
        },
      }
    },
  }
</script>

 問題解決後のコード

exsample.vue
<template>
    <label
      v-for="(checkBox, key) in list"
      :key="key"
      :for="sample' + key"
    >
        <input
          :id="'sample' + key"
          v-model="checkBox.checkboxStatus"
          type="checkbox"
          name="sample[]"
          class="input"
          @change=" e => changeHandle(e, 'sample[]', key, list.id,)"
        />
    <label>
</template>

<script>
  export default {
    data() {
      return {
        list: {
          { id: 1, checkboxStatus: false },
          { id: 2, checkboxStatus: false },
        },
      }
    },
    methods: {
      changeHandle(e, eln, index, id) {
        const isChecked = e.target.checked;
        document.form[eln][index].value = isChecked ? id : null;
      },
    },
  }
</script>

解説

checkboxをクリックした際に変わる値はtarget.valueではなく、target.checkedだった。
target.checkedの値はBooleanだが、submit時に送られる値はvalueなので
requestから見ると"on"という値になっていた~~(nullではなく"on"になるのはvueの仕様??)~~
@tomoyuki_okawa さんにコメントで教えていただきました、ありがとうございます!
HTMLの仕様みたいです、恥ずかしながら知りませんでした💦
https://developer.mozilla.org/ja/docs/Web/HTML/Element/input/checkbox

そのため、無理やりではあるがDOMを取得しtarget.checkedの結果に応じvalueにpostしたい結果を代入するという方法を取りました。
もっと良い方法をご存知の方がいらっしゃいましたらご教示いただけると幸いです!

4
0
2

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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?