'Can't find a way to access input field with Javascript
I'm trying to find a way to change the value of the input field below using Javascript. The problem is that I can't find any id or name of the input field and thus, not sure how to access it.
I have used document.getElementById to access other fields to change their value but since this input field does not have an Id I'm not sure how to approach it. The code below is not my own and thus I can't simply add an id. Any ideas on how to solve the problem?
<ul class="form-control recipient-input ac-input rounded-left">
<li class="input">
<input type="text" tabindex="1" autocomplete="off" aria-autocomplete="list" aria- expanded="false" role="combobox" aria-haspopup="false">
</li>
</ul>
Solution 1:[1]
const el = document.querySelector('input[type=text]');
console.log(el)
<ul class="form-control recipient-input ac-input rounded-left">
<li class="input">
<input type="text" tabindex="1" autocomplete="off" aria-autocomplete="list" aria- expanded="false" role="combobox" aria-haspopup="false">
</li>
</ul>
Solution 2:[2]
<input /> elements should always be enclosed within a <form />.
By giving a name to your <form name="my-form"><input name="firstName" /></form>, it become easy to access any fields of the form without having to use fixed id in your HTML and make those <form /> reusable anywhere in your view.
window.onload = bindEvents
function bindEvents() {
const { name } = document.forms['my-form']
name.addEventListener('keypress', onChangeName, true)
}
function onChangeName(event) {
console.log(event.target.value)
}
<form name="my-form">
<ul>
<li>
<label for="name">Name</label>
<input name="name" />
</li>
</ul>
</form>
Solution 3:[3]
I think "document.querySelector" is enough to do that job. Below code might be useful.
document.addEventListener("DOMContentLoaded", function() {
var elm = document.querySelector('.recipient-input input');
// Get the full DOM object of input element
console.log(elm);
// Get input value
var val = elm.value;
console.log(val);
// Get any attribute
var attr = elm.getAttribute("role");
console.log(attr);
// Set input value
elm.value = "This is a form element";
console.log(elm.value);
// Change any attribute
elm.setAttribute("role", "primary");
console.log(elm.getAttribute("role"));
});
<ul class="form-control recipient-input ac-input rounded-left">
<li class="input">
<input type="text" tabindex="1" autocomplete="off" aria-autocomplete="list" aria- expanded="false" role="combobox" aria-haspopup="false">
</li>
</ul>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ankan Bag |
| Solution 2 | |
| Solution 3 | fatih |
