Prince
Prince

Reputation: 117

Fetch html data attribute with Vue js onchange

I would like to know how I can the data attribute of form select using Vue js. Here is the select

   <form method="post">
            <select @change="onChange" id="option" class="form-control 
                 sectionprice" required="" name="option">
        <option disabled="disabled" value="">Select Option</option>
                        <option data-type="Option" data-value="Mac Pro 128 GB" data-price="915.56">Mac Pro 128 GB</option><option data-type="Option" data-value="Mac Pro 254 GB" data-price="1300">Mac Pro 254 GB</option></select>
     <input name="realprice" type="hidden" :value="dataprice"/> 
      </form>
<script>
    var imagesection = new Vue({
        el: '#pricesection',
        data: {
            dataprice:'';
        },
        methods:{
        onChange(){
                this.dataprice = this.dataset.price
        },
        }

    })

</script>

What I am trying to achieve here is when an option is selected, using the @change, I can get the data-price of the selected option. Then the value of the hidden input field which is realprice will be updated with the data-price value.

Guys I will appreciate if someone help me out.

Upvotes: 3

Views: 3631

Answers (1)

Moumen Soliman
Moumen Soliman

Reputation: 1674

I've updated it for you, you will use @change with event to get the selected target,

<div id="pricesection">
<form method="post">
   {{dataprice}}
   {{datavalue}}
  <select @change="onChange" id="option" class="form-control 
                 sectionprice" required="" name="option">
    <option disabled="disabled" value="">Select Option</option>
    <option data-type="Option" data-value="Mac Pro 128 GB" data-price="915.56">Mac Pro 128 GB</option>
    <option data-type="Option" data-value="Mac Pro 254 GB" data-price="1300">Mac Pro 254 GB</option>
  </select>
  <input name="realprice" type="hidden" :value="dataprice" />
</form>
</div>


<script>
new Vue({
  el: "#pricesection",
      data: {
        dataprice: '',
        datavalue: ''
      },
      methods: {
        onChange(e) {
          if (e.target.options.selectedIndex > -1) {
            const theTarget = e.target.options[e.target.options.selectedIndex].dataset;
            this.dataprice = theTarget.price
            this.datavalue = theTarget.value
          }
        }
      }
})

</script>

Upvotes: 5

Related Questions