window.onload = initialise;function initialise() { var fields = document.getElementsByTagName("input"); for (var i = 0; i < fields.length; i += 1) { var id = this.id; var msg = document.getElementById(id + "_msg"); /** * Now the function checkField() has access to * - the field -> through this * - the message -> through msg */ fields[i].addEventListener("blur", checkField(msg)); } }function checkField(msg) { if (this.value === "") { msg.innerHTML = "LOL"; }}
Hello,
Do you know Facebook?
I am trying to recreate the same signup page that they have.
If you try to signup but leave all fields empty and click on the signup button, some JavaScript code will stop you. Likewise, if you click on any of the fields and leave it empty, some JavaScript code will let you know that the field needs improving even before you click on submit.
To achieve the same, I have decided to have a function called "checkField" that runs every time we trigger the "blur" event. (Later I will also make a function called "checkFields" that will check all fields when you click submit ..or all the fields that haven't been OKed yet). I want my code to work regardless of the actual id names and the amount of input fields present at any given time.
What I have done so far does not work unfortunately. I think it's due to the fact that the variables "id" and "msg" get reset at every loop cycle, but I am not too sure. Anybody here kind enough to be able / willing to point me in the right direction? Would OOP techniques such as creating a class "Field" work? Any pointer would be very much appreciated. I am kind of new to JS and web dev so..
Cla