简体   繁体   中英

Alpine JS change label / textbox value based on select option

Is it possible to change a label and textfield value based on a select option in AlpineJS?

On page load, i would like the select option to be local and the label below to be 'Define' and the textbox value to be 'define here', but if someone chooses remote then the label to read 'Remote Define' and the textfield value to be 'remote define here'.

Is that possible with AlpineJS? The code i have is as follows;

<div>
    <label for="location">Location</label>
    <div>
        <select id="location">
            <option value="local">Local</option>
            <option value="remote">Remote</option>
        </select>
    </div>
</div>

<div>
    <label for="define">Define</label>
    <input id="define" type="text" autocomplete="off">
</div>

With Alpine.js you can use x-model to 2-way bind an input/select (2-way because a value update in the component state/JS will update the input/select and a change to the input/select will update component state/value in JS). You can use x-model to deal with the location value updates. Note that you need a wrapping element with x-data on it.

Alpine.js also provides a way to set the text ( x-text ) and to bind to arbitrary attributes x-bind , in your case, you want to set the placeholder value so x-bind:placeholder .

In full:

<form x-data="{ location: 'local' }">
<div>
    <label for="location">Location</label>
    <div>
        <select id="location" x-model="location">
            <option value="local">Local</option>
            <option value="remote">Remote</option>
        </select>
    </div>
</div>

<div>
    <label for="define" x-text="location === 'local' ? 'Define' : 'Remote Define'"></label>
    <input id="define" type="text" autocomplete="off" x-bind:placeholder="location === 'local' ? 'define here' : 'remote define here">
</div>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM