Isus Isus - 6 months ago 13
HTML Question

Form validation for textfield not working?

In javascript, I´m supposed to create a function that checks if a textfield within a form is empty. If it is and the user clicks submit, the user will not be allowed to proceed. I found what I considered a suitable solution to this on w3schools (http://www.w3schools.com/js/js_validation.asp). I´ve checked more times than I can remember and everything seems to be in order, but it´s not working!! Instead, when the submit button is clicked, the website calls a different function I have in javascript which it is not supposed to do...

HTML code

Other code
<p>
<form method="post" name="form" action="" onsubmit="return validateName()">
<label for="fullName">Namn: </label><input id="fullName" class="text" name="namn" type="text"> </input>
</p>
<p>
<label for="epost">Epost: </label><input id="epost" class="text" name="epost" type="email"> </input>
</p>
<p>
<input id="submit" type="submit" value="Skicka"> </input>
</p>
</form>
Other code


Javascript code

function validateName() {
var a = document.forms["form"]["namn"].value;
if (a == null || a == "") {
alert("Name required");
return false;
} else {
return true;
}
}


Clicking the submit button should call this function above (validateName), but instead it calls this function:

function alert() {
return confirm("Do you really wish to leave this website?");
}


I´ve looked through my code multiple times and can´t find anything that seems to be out of place. Can any of you find anything wrong? And maybe suggest a solution that solves my problem so my function will work properly?

I would be very grateful if someone could help me resolve this matter!

Answer

alert is a predefined function that you are using correctly once and incorrectly the second time. Simply change the name of YOUR alert function to something else, or just use confirm as it was intended and leave out the function alert part

Correct:

alert("Name required");

Incorrect:

function alert() { 
   return confirm("Do you really wish to leave this website?");
}

one solution is to do this:

function confirm_leaving(){
    return confirm("Do you really wish to leave this website?");
}