I am stuck and need help. I have 5 text boxes: txt1
, txt2
, txt3
, txt4
and txt5
, and there is a function func1()
. I want that if there are any changes in any of these text boxes then the function func1()
will be called. Can you please help me with how I can do this in JavaScript?
I am stuck and need help. I have 5 text boxes: txt1
, txt2
, txt3
, txt4
and txt5
, and there is a function func1()
. I want that if there are any changes in any of these text boxes then the function func1()
will be called. Can you please help me with how I can do this in JavaScript?
- 1 Answers below are good. If you happen to be unaware of jQuery, you should check it out. – rkw Commented Jan 31, 2012 at 8:53
6 Answers
Reset to default 3Link the onchange event to your func1()
It will be something like:
<input type="text" onchange="func1()">
<input type="text" onchange="func1()">
<input type="text" onchange="func1()">
<input type="text" onchange="func1()">
<input type="text" onchange="func1()">
(The id/name was not written.)
You could subscribe to the onchange
event in those textboxes and call the function:
<input type="text" name="txt1" id="txt1" onchange="func1();" />
<input type="text" name="txt2" id="txt2" onchange="func1();" />
...
or do it unobtrusively:
<input type="text" name="txt1" id="txt1" />
<input type="text" name="txt2" id="txt2" />
...
and then in your javascript file:
window.onload = function() {
document.getElementById('txt1').onchange = func1;
document.getElementById('txt2').onchange = func1;
...
};
or in a loop:
window.onload = function() {
for (var i = 1; i <= 5; i++) {
document.getElementById('txt' + i).onchange = func1;
}
};
<SCRIPT TYPE="text/javascript">
function function1()
{
alert("changed");
}
</SCRIPT>
<INPUT NAME="txt1" onChange="function1()"><BR>
<INPUT NAME="txt2" onChange="function1()"><BR>
<INPUT NAME="txt3" onChange="function1()"><BR>
If you need to get the reference to the element then
<input type="text" name="txt1" id="txt1" onchange="func1(this);" />
<input type="text" name="txt2" id="txt2" onchange="func1(this);" />
function func1(item){
// you have the reference to the item
}
I see every answer using the "onchange" events in HTML. This is bad practice. See Unobtrusive Javascript to understand why.
I'd remend using document.getElementById('').addEventListener('change', function() {});
, but the cross-browser support of this is not the best, so this is why I remend using jQuery.
In jQuery, you just add the same class to your textboxes, and you can do this :
$('.textBoxes').change(function() {});
I usually don't remend jQuery when somebody asks for javascript, but this case clearly asks for cross-browser patibility.
Use onchange
. <input type="text" id="txt1" onchange="func1()" />
See JavaScript Event onChange