AlpineJs Extract value from select[option]

Tags: ,



Trying to use the x-model.number to get values from select option to calculate the values. Using the below input text works. How do I translate it on the select option?

<div x-data="{first: 0, second: 0}">
  <input type="text" x-model.number="first"> + <input type="text" x-model.number="second"> =
        <output x-text="first + second"></output>
 </div>


<div x-data="{chromeNow: 0, chromeNatural: 0 }">
       <select>
           <option value="7499.00" x.model.number="chromeNow">1</option>
           <option value="6900.00" x.model.number="chromeNow">2</option>
      </select>
      <select >
         <option value="6900.00" x.model.number="chromeNatural">1</option>
         <option value="1200.00"  x.model.number="chromeNatural">2</option>
      </select>

   <h3 x-text="chromeNow + chromeNatural"> </h3>
</div>

Answer

I believe it should work by putting the x-model on the select instead of the option. To make the selected state be correct, it’s also probably a good idea to bind the value to the number representation.

<div x-data="{chromeNow: 0, chromeNatural: 0 }">
       <select x-model.number="chromeNow" >
           <option :value="7499.00">1</option>
           <option :value="6900.00">2</option>
      </select>
      <select x-model.number="chromeNatural">
         <option :value="6900.00">1</option>
         <option :value="1200.00">2</option>
      </select>

   <h3 x-text="chromeNow + chromeNatural"> </h3>
</div>


Source: stackoverflow