Using the sample code from W3schools I am trying to set up a single event handler that will fire when any of multiple 'input' elements in a form are changed.
What I want is to receive the <input name=xxxx> name parameter
As I understand it, p1 and p2 should contain the event and the name of the <input name=xxxx> field that fired the event. Instead I get a reference error, "p1 is not defined" from the event handler. On search I have found many convoluted solutions to this question, some of which I don't understand, but none that actually solve my problem. What am I doing wrong?
function field_check(event) {
var the_input = event.target.id;
alert("field_check: event was: " + event + "\nand the entry field was: " + the_input);
}
document.getElementById("add_data").addEventListener("change", field_check);
input {
background-color: lightblue;
}
input:focus {
background-color: yellow;
}
<form name=add_data id=add_data>
<input type="text" class="ship" name="fname" id="fname" autofocus><br \>
<input type="text" class="ship" name="lname" id="lname" required><br />
<input type="text" class="ship" name="addr1" id="addr1"><br />
<input type="text" class="ship" name="addr2" id="addr2"><br />
<input type="text" class="ship" name="city" id="city"><br />
<input type="text" class="ship" name="p_code" id="p_code">
</form>
You mean to do
var s = document.getElementById("add_data");
s.addEventListener("change", function(event) {
field_check(event, event.target.name);
});
or even simpler
document.getElementById("add_data").addEventListener("change", field_check);
and have
function field_check(event) {
console.log(event.target.name);
}
function field_check(event) {
console.log(event.target.name);
}
document.getElementById("add_data").addEventListener("change", field_check);
input {
background-color: lightblue;
}
input:focus {
background-color: yellow;
}
<form name=add_data id=add_data>
<input type="text" class="ship" name="fname" id="fname" autofocus><br \>
<input type="text" class="ship" name="lname" id="lname" required><br />
<input type="text" class="ship" name="addr1" id="addr1"><br />
<input type="text" class="ship" name="addr2" id="addr2"><br />
<input type="text" class="ship" name="city" id="city"><br />
<input type="text" class="ship" name="p_code" id="p_code">
</form>