I have the following code which is checking to see if the user has entered anything into any of the fields, and if there any information in any field then it asks do you want to leave, but its not working
//If form is not empty, ask do you want to leave
window.onbeforeunload = confirmExit;
function confirmExit() {
var a = document.forms["enquiryForm"]["Name"].value;
var b = document.forms["enquiryForm"]["FromEmailAddress"].value;
var c = document.forms["enquiryForm"]["TelephoneNumber"].value;
var d = document.forms["enquiryForm"]["Message"].value;
if (a != "" || b != "" || c != "" || d != "") {
return true;
}
<form action="#contact" language="en" method="post" name="enquiryForm" novalidate="novalidate">
<input data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />
<input data-val="true" data-val-required="The FromEmailAddress field is required." id="FromEmailAddress" name="FromEmailAddress" type="email" value="" />
<input data-val="true" data-val-required="The TelephoneNumber field is required." id="TelephoneNumber" name="TelephoneNumber" type="tel" value="" />
<textarea cols="20" data-val="true" data-val-required="The Message field is required." id="Message" name="Message" rows="2">
</textarea>
<button type="submit">Submit</button>
</form>
I’m thinking a neater way would be rather than having to list the input fields, is it possible to just check if any input or textfield is not empty
Changed the if or statement to below and still doesn’t work, I’m not sure what I’m doing wrong
Yours is at least bringing up the message, but what yours is also doing is bringing up the message if all the form fields are empty, what I was going to do was check if they have entered anything in any of the fields and then invoke the message, if its empty don’t worry just allow them to leave.
But when I check in my browser, I don’t get any message in any situation
I’m building this is in Visual Studio, and building the site in ASP.Net using the MVC framework and testing it locally, but I think this shouldn’t impact on the script not running.
If there’s a scripting syntax error then that will prevent the script from running at all. Check your browser console to find out if it reports any errors there.
LOL Paul, your going to shoot me, I was missing a closing curly bracket.
I’m used to working in Dreamweaver and it would have picked this up, it doesnt in Visual Studio, but that has solved it. Much appreciate your help as always
Here we go if anyone needs the final solution (with closing curly bracket)
//If form is not empty, ask do you want to leave
window.onbeforeunload = confirmExit;
function confirmExit(evt) {
var a = document.forms["enquiryForm"]["Name"].value;
var b = document.forms["enquiryForm"]["FromEmailAddress"].value;
var c = document.forms["enquiryForm"]["TelephoneNumber"].value;
var d = document.forms["enquiryForm"]["Message"].value;
if (a != "" || b != "" || c != "" || d != "") {
return true;
}
}