Kirill Vorobjov Kirill Vorobjov - 7 months ago 41
Javascript Question

Call a Javascript function from another JS file

Good day!(Beginner here)

I have two JS files ( or is it called module ? ) , in the first JS file I have my "login" script and the second JS file i use in my HTML file ( so the second one should call the first one). So I've writen something like this to call the script from the first file :

function testAnmelden(anmelden) {
anmeldeForm(anmelden);
}


So the script works but it transfers me to another page even if there was an error. (Both are added in HTML file

Here is my first File script (sorry if too long ) :

function anmeldeForm(anmelden) {
var Fehler = [];
var falsheZeichen = /^[\w ]+$/;
//Shows an Error message when the field is empty or the personal number is smaller than 5 or biger than 8 numbers.
if (anmelden.persnfeld.value == "") {
anmelden.persnfeld.style.background = "Red";
Fehler.push("Das Personalnummerfeld ist leer!");
}

else if ((anmelden.persnfeld.value.length < 5) || (anmelden.persnfeld.value.length > 8)) {
anmelden.persnfeld.style.background = "Red";
Fehler.push("Die Personalnummer mus zwischen 5 und 8 Zeichen lang sein")
}
else {
anmelden.persnfeld.style.background = "";
}

if (anmelden.kwortfeld.value == "") {
anmelden.kwortfeld.style.background = "Red";
Fehler.push("Das Kennwortfeld ist leer!");
}
//Shows an Error message when "@/\$ are used
else if (!falsheZeichen.test(anmelden.kwortfeld.value)) {
anmelden.kwortfeld.style.background = "Red";
Fehler.push("Das Kennwortfeld enthalt falsche Zeichen");
}
else if ((anmelden.kwortfeld.value.length < 5) || (anmelden.kwortfeld.value.length > 8)) {
anmelden.kwortfeld.style.background = "Red";
Fehler.push("Das Kennwort muss zwitschen 5 und 8 Zeichen lang sein");
}
else {
anmelden.kwortfeld.style.background = "";
}

if (Fehler.length > 0) {

var meldung = "Error:\n\n";
for (var i = 0; i < Fehler.length; i++) {
meldung += Fehler[i] + "\n";

}
alert(meldung);
return false;
}
return true


}

How do i call a function written in one JS file from another?

How can i make "function" popup in the second JS file like that , is this even possible ?

Answer

So the script works but it transfers me to another page even if there was an error.

event.preventDefault() is what you are looking for.

HTML

<form onsubmit="foo(event)"></form>

Javascript

function foo(event) {
  event.preventDefault(); // This will prevent the unwanted redirection
}
Comments