简体   繁体   中英

Is there a vanilla JavaScript way to change the value of an input field

What I am trying to achieve is for the value of the id="origin" input field to be updated as you type in the id="pickup" field.

 const pickup = document.querySelector('#pickup') const dropoff = document.querySelector('#dropoff') const origin = document.querySelector('#origin') const destination = document.querySelector('#destination') const submit = document.querySelector('#submitForm') pickup.addEventListener('input', (e) => { origin.value = e.target.value })
 .hidden { opacity: 0; }
 <form> <div class="form-group"> <label for="pickup">Pickup</label> <input type="text" class="form-control" id="pickup" aria-describedby="pickupHelp"> <input type="text" class="form-control hidden" id="origin" value="empty"> <small id="pickupHelp" class="form-text text-muted">Enter your pickup location</small> </div> <div class="form-group"> <label for="pickup">Drop-off</label> <input type="text" class="form-control" id="dropoff" aria-describedby="dropoffHelp"> <input type="text" class="form-control hidden" id="destination" value=""> <small id="dropoffHelp" class="form-text text-muted">Enter your drop-off location</small> </div> <button type="submit" class="btn btn-primary" id="submitForm">Submit</button> </form>

I found the solution I was looking for. Sorry for not clearly stating what I wanted to do.

pickup.addEventListener('input', (e) => {
//changed to .defaultValue instead of just .value
    origin.defaultValue = e.target.value
})

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