JavaScript Refreshes Instead of Changing Pages - javascript

I am unable to figure out why my page will not redirect to the set page. Whenever the condition is met, the page simply refreshes. I have gone into the browser console and pasted my redirect code, and it does redirect.
Full JavaScript Function:
function formSubmit(){
var formFN = document.getElementById("fName");
var formLN = document.getElementById("lName");
if( formFN.value.length == 0 || formFN.value == null){
window.alert("Please enter your first name.");
return false;
}
else if( formLN.value.length == 0 || formLN.value == null){
window.alert("Please enter your last name.");
return false;
}
else
{
document.location = "resultPage.html";
return false;
}
}
HTML Part:
<div id="form">
<form action="">
<h3>Thanks for visiting!</h3>
<label for="fName">First Name:</label>
<input type="text" id="fName" value="">
<br>
<label for="lName">Last Name:</label>
<input type="text" id="lName" value="">
<br>
<button onclick="formSubmit();">
Submit
</button>
<!-- <input type="submit" value="Submit" onclick="formSubmit();"> -->
</form>
</div>

By default, button elements have a type attribute of submit. Based on your question, you probably want this instead:
<button type="button" onclick="formSubmit();">
Submit
</button>
If you want a more general solution, you'd be better off capturing and handling the submit event on the form since things like pressing return in an input would trigger a submit as well.
window.addEventListener("load", function() {
document.getElementById("form").getElementsByTagName("form")[0].addEventListener("submit",function(event) {
event.preventDefault(); // Stop the normal action for this event
var formFN = document.getElementById("fName");
var formLN = document.getElementById("lName");
if( formFN.value == null || formFN.value.length == 0 ){
alert("Please enter your first name.");
}
else if( formLN.value == null || formLN.value.length == 0 ){
alert("Please enter your last name.");
}
else {
document.location = "resultPage.html";
}
});
});
<div id="form">
<form>
<h3>Thanks for visiting!</h3>
<label for="fName">First Name:</label>
<input type="text" id="fName" value="">
<br>
<label for="lName">Last Name:</label>
<input type="text" id="lName" value="">
<br>
<button>Submit</button>
</form>
</div>
Edit: It occurs to me that you should check for nulls before checking for length. (If .value is null then checking .value.length will throw an error.) Adjusted code accordingly.

Related

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

Can not run document.getElementById

I just wrote a simple javascript to submit a form.
<div class=login>
<fieldset>
<legend>Login</legend>
<form id="form" method="get" action="summary_iframe.html" onsubmit="return validate()">
User: <input type="text" id="userAc" value="" name="userAc"><br>
Password: <input type="text" id="userPw" value="" name="userPw"><br>
This is the function, check that both user and password are not blank and there is no intervening space in use.
function validate(){
var userAc = document.getEmelentById('userAc').value;
var userPw = document.getEmelentById('userPw').value;
if(userAc.length == 0 || userPw.lenth == 0 || userAc.indexOf(' ')>-1 || userPw.indexOf(' ')>-1)
{
alert("Please input again!");
return false;
}
else
{
checkLogin(userAc, userPw);
return true;
}
}
But it does not work, I used a browser to debug and when it's running this line, it quits form the function.
var userAc = document.getEmelentById('userAc').value;
Please tell me what's wrong. Thanks!
Please alter your function as below.
function validate(){
var userAc = document.getElementById('userAc').value;
var userPw = document.getElementById('userPw').value;
if(userAc.length == 0 || userPw.lenth == 0 || userAc.indexOf(' ')>-1 || userPw.indexOf(' ')>-1)
{
alert("Please input again!");
return false;
}
else
{
checkLogin(userAc, userPw);
return true;
}
}
You need to use as document.getElementById('userAc').value, instead of document.getEmelentById('userAc').value. Hereafter please check your browser console before you post any question here. Thanks
You have missed Submit Button.
<form id="form" method="get" action="summary_iframe.html" onsubmit="return validate()">
User: <input type="text" id="userAc" value="" name="userAc"><br>
Password: <input type="text" id="userPw" value="" name="userPw"><br>
<input type="submit" value="submit" name="btnSubmit">
</form>

Submitting Form W/ Javascript

My javascript form validation is working correctly. I want it so that when the form is valid, it will go to a different page. I am having trouble with that part. I tried using the document object to submit it if everything is valid but its not working
Javascript:
function func(){
var first = document.getElementById('fname').value;
var last = document.getElementById('lname').value;
var email = document.getElementById('mail').value;
var phone = document.getElementById('phone').value;
var val_phone = /^\(\d{3}\)\d{3}-\d{4}$/;
var val_mail = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if ( first == "" || last == "" || email == "" || phone == "")
{
alert("Do not Leave Any Blank Answers");
return;
}
if ( phone != phone.match(val_phone) || email != email.match(val_mail) )
{
alert("Incorrect Format! \n Please Check Email and Phone Number! ");
return;
}
else {
document.forms["survey"].sumbit();
}
}
HTML:
<form id="survey" name="survey" action="SlideShow.html" method="post">
First Name:<br>
<input type="text" id="fname" name="fname" required="required"><br>
Last Name:<br>
<input type="text" id="lname" name="lname" required="required"><br>
Email:<br>
<input type="email" id="mail" name="mail" required="required"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone" required="required"><br><br>
<input type="button" value="Submit" onclick="func()">
</form>
Your else block is calling sumbit(), but the proper spelling is submit().
Additionally, I recommend getting in the habit of a strict === check as opposed to a ==.
Here's a JSFiddle with the updated and refactored code:
http://jsfiddle.net/cyeof94g/

Forum submit button is redirecting me to an unknown webpage?

I am trying to create a "contact us" forum with html.
This is my current html:
<form id="contact_form" name="contact_form" method="post" action="validate()">
<div class="row">
<label for="name" class="desc" style="font-size: 30px;">Your name:</label><br />
<input id="name" class="input" name="name" type="text" value="" size="50" /><br />
</div><br /><br />
<div class="row">
<label for="email" class="desc" style="font-size: 30px;">Your email:</label><br />
<input id="email" class="input" name="email" type="text" value="" size="50" /><br />
</div><br /><br />
<div class="row">
<label for="message" class="desc" style="font-size: 30px;">Your message:</label><br />
<textarea id="message" class="input" name="message" rows="8" cols="50"></textarea><br />
</div>
<div class="row"><br />
<input id="submit_button" type="submit" value="Send email"/>
</div>
</form>
And my javascript:
function validate() {
//Make sure name is filled out
var x = document.forms["contact_form"]["name"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
//Make sure email is filled out
var x = document.forms["contact_form"]["email"].value;
if (x == null || x == "") {
alert("Email must be filled out");
return false;
}
//Make sure message is filled out
var x = document.forms["contact_form"]["message"].value;
if (x == null || x == "") {
alert("Message must be filled out");
return false;
}
//Validate email
var x = document.forms["contact_form"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid email");
return false;
}
}
For some reason when I hit "submit" it takes me to a page called "validate()" How can I make it so that when I click submit it EXECUTES the function validate(), not just take me to a page called validate()...
NOTE: Nevermind the php, right now focus on the html and javascript
It redirects it to that page because you are setting the action to go there. That does not execute JavaScript. You are looking for onsubmit.
Change action="validate()" to onsubmit="return validate();"
And as always, it would be better to set it unobtrusively instead of inline.

form not validating - javascript

bit of a noob with form validation. I'm trying to get this form to validate on the required fields, and something's amiss. Here's what I'm working with:
html:
<form action="../visit/thankyou.html" method="post" id="vsurvey">
<input type="hidden" name="id" value="503" />
<fieldset>
<legend>Group and Coordinator Information</legend>
<label><span>Group Leader Name<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8149" />
</label>
<label><span>Email<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8155" />
</label>
<label><span>Phone<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8156" />
</label>
<label><span>School/Organization<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8159" />
</label>
<label><span>Program</span>
<input type="text" name="question_8180" />
</label>
<label><span>Grade(s)</span>
<input type="text" name="question_8181" />
</label>
<label><span>Number of Participants<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8182" />
</label>
</fieldset>
<fieldset>
<label><span>Preferred Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8185" name="question_8185" />
</label>
<label><span>Second Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8186" name="question_8186" />
</label>
<label><span>Third Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8187" name="question_8187" />
</label>
<label>Special Accommodations
<input type="text" name="question_8174" />
</label>
</fieldset>
<label>What is the purpose or desired outcome of this visit?
<textarea name="question_13026"></textarea>
</label>
<label>How did you learn about our Group Visit Program?
<textarea name="question_8176"></textarea>
</label>
<label>Comments
<textarea name="question_8184"></textarea>
</label>
<input type="submit" id="sbutton" value="Submit Request" />
</form>
js:
function validateForm() {
var x = document.forms["vsurvey"]["question_8149"].value;
if (x == null || x == "") {
alert("Please fill in the Group Leader's name.");
return false;
}
var x = document.forms["vsurvey"]["question_8155"].value;
if (x == null || x == "") {
alert("Please fill in the email field.");
return false;
}
var x = document.forms["vsurvey"]["question_8156"].value;
if (x == null || x == "") {
alert("Please fill in the phone field.");
return false;
}
var x = document.forms["vsurvey"]["question_8159"].value;
if (x == null || x == "") {
alert("Please fill in the School/Organization field.");
return false;
}
var x = document.forms["vsurvey"]["question_8182"].value;
if (x == null || x == "") {
alert("Please indicate the number or participants.");
return false;
}
var x = document.forms["vsurvey"]["question_8185"].value;
if (x == null || x == "") {
alert("Please enter your preferred date.");
return false;
}
var x = document.forms["vsurvey"]["question_8186"].value;
if (x == null || x == "") {
alert("Please enter your second date preference.");
return false;
}
var x = document.forms["vsurvey"]["question_8187"].value;
if (x == null || x == "") {
alert("Please enter your third date preference.");
return false;
}
}
http://jsfiddle.net/blackessej/9a6BJ/1/
Currently the form submits the info anyway, but without sending the user to the thankyou page, if all required fields aren't filed in. If all required fields are filed, the thankyou page gets called.
You're not calling validatorForm. Your input button needs to be the following
<input type="submit" id="sbutton" value="Submit Request" onclick="return validateForm()" />
Or use the onsubmit event of your form
<form action="../visit/thankyou.html" method="post" id="vsurvey" onsubmit="return validateForm()">
You need to create an onSubmit event to call validateForm:
document.getElementById('vsurvey').onsubmit = validateForm;

Categories