alpine.js

Accessing a datalist element's id using AlpineJS


Is it possible to get the id value of a selected option in the example below using AlpineJS?

I'm trying to build a form that submits the id of a selected element instead of the value. In this example, when a user selects 'Firefox' from the list and submits the form, the value 1 should be submitted for the value of browserId instead of Firefox

<label for="browser">Choose your browser from the list:</label>

<input type="text" list="browsers" name="browser" id="browser">
  <datalist id="browsers">
    <option id=1 value="Firefox">
    <option id=2 value="Edge">
    <option id=3 value="Chrome">
  </datalist>

<input id='browserId' type='hidden' value="Selected Browser's id should show up here"/>

I've tried using the x-model directive on #browser input element and x-bind directive on the #browserId element, but I only get the value and not the id.


Solution

  • If <datalist> is expendable in favor of <select> you can do this:

    <div x-data="{browser_id: 1}">
    
       <label>Choose your browser from the list:</label>
    
         <select id="browsers" name="browsers" x-on:change="browser_id = $el.value">
           <option value="1">Firefox</option>
           <option value="2">Edge</option>
           <option value="3">Chrome</option>
         </select>
    
       <input id='browserId' type='hidden' :value="browser_id" />
    
    </div>