Reputation: 21
<script>
function disableBtn() {
document.getElementsByTagName("INPUT")[1].removeAttribute("disabled");
}
</script>
<form>
<p>
<label for="uname">* User Name :</label>
<br>
<input type="text" name="txtuname" id="uname" onclick="disableBtn()" value="">
</p>
<div style="text-align:center">
<p>
<input name="username" type="submit" id="submit" value="Change Username" disabled="disable">
</p>
</div>
<p>
<label for="fullname">* Full Name :</label>
<br>
<input type="text" name="txtfullname" id="fullname" value="">
</p>
<div style="text-align:center">
<p>
<input name="fullname" type="submit" id="submit" value="Change Fullname" disabled="disable">
</p>
</div>
<p>
<label for="address">* Address :</label>
<br>
<input type="text" name="txtaddress" id="address" value="">
</p>
<div style="text-align:center">
<p>
<input name="address" type="submit" id="submit" value="Change Address" disabled="disable">
</p>
</div>
</form>
I want to add an onclick
event in each input tag which executes the function disableBtn
, but I want this code to work on any input I click. I do not want to have to give a number like this :
document.getElementsByTagName("INPUT")[1].removeAttribute("disabled");
for every input element.
I think I should use this but I don't know where to put it.
Upvotes: 1
Views: 80
Reputation: 3888
You want to loop over every input element and add an event? document.getElementsByTagName("input")
returns an array, so you can use a loop to go over it.
JavaScript:
// This is a function which disables an input element
// Notice I used "this" instead of document.getElementsByTagName("input")[some number]
// "this" refers to the input element that was clicked
function disableBtn() {
this.parentNode.nextElementSibling.querySelector('input[type="button"]').disabled = false;
}
// Get every single input element
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; ++i) {
// Loop through the input elements, and add a "click" event
var input = inputs[i];
input.addEventListener("click", disableBtn, false);
}
Upvotes: 1
Reputation:
Code:
Change your function to this:
function disableBtn(el) {
el.parentNode.nextElementSibling.querySelector("input").disabled = false;
}
And the handler to this:
onclick="disableBtn(this)"
DEMO: http://jsfiddle.net/dcg8gzqt/
Explanation:
So now the handler passes the current element that was clicked to the disableBtn
function.
That function then...
.parentNode
.nextElementSibling
, which is the next div
, div
using .querySelector()
for the first input
it finds..disabled
property of the input
to false
Upvotes: 0