JavaScript
x
13
13
1
const btn = document.getElementById("btn");
2
const inputfield = document.getElementById("username");
3
4
inputfield.addEventListener("keyup", function(e) {
5
const val = e.target.value;
6
if (val === "") {
7
btn.disabled = true;
8
btn.style.backgroundColor = "grey";
9
} else {
10
btn.disabled = false;
11
btn.style.backgroundColor = "orange";
12
}
13
})
JavaScript
1
4
1
<div class="container">
2
<input id="username" placeholder="Username" class="input" />
3
<button disabled id="btn" type="button" class="button">Submit</button>
4
</div>
Now the issue is that it only works for one input and the associated button field it does not work for another pair of input field and button , so what changes should i make in the above javascript code in which it runs for as many as input field and button i want?
Please can anyone help me in this. Thank you
If you have full jquery code it’s also accepted.
Advertisement
Answer
My approach was to put the input and button in a div with a custom class. And just loop over every div, get the child inputs and buttons and just use your existing code for every div.
JavaScript
1
17
17
1
const btns = document.getElementsByClassName('inputButton');
2
3
for (let i = 0; i < btns.length; i++) {
4
let input = btns[i].querySelector('input');
5
let button = btns[i].querySelector('button');
6
7
input.addEventListener("keyup", function(e) {
8
const val = e.target.value;
9
if (val === "") {
10
button.disabled = true;
11
button.style.backgroundColor = "grey";
12
} else {
13
button.disabled = false;
14
button.style.backgroundColor = "orange";
15
}
16
});
17
}
JavaScript
1
14
14
1
<div class="container">
2
<div class="inputButton">
3
<input id="username" placeholder="Username" class="input" />
4
<button disabled id="btn" type="button" class="button">Submit</button>
5
</div>
6
<div class="inputButton">
7
<input id="username" placeholder="Username" class="input" />
8
<button disabled id="btn" type="button" class="button">Submit</button>
9
</div>
10
<div class="inputButton">
11
<input id="username" placeholder="Username" class="input" />
12
<button disabled id="btn" type="button" class="button">Submit</button>
13
</div>
14
</div>