This code isn't doing anything when I submit the form. What am I doing wrong? In the HTML, an error message is shown or hidden based on a class.
I hope you can help me figure out this problem. Thanks in advance.
$(document).ready(function() {
function validateForm() {
var first_name = $("#first_name").value;
var last_name = $("#last_name").value;
var phone = $("#phone").value;
var email = $("#email").value;
var code = $("#vali_code").value;
var ssn = $("#ssn").value;
var income = $("#nm_income").value;
var error = $(this).find("span.error_txt").removeClass(".hidden").addClass(".show");
var emailReg = /^([w-.]+#([w-]+.)+[w-]{2,4})?$/;
if (first_name === "") {
error;
}
if (last_name === "") {
error;
}
if (email === "" || email !== emailReg) {
error;
}
if (phone === "" || phone < 9) {
error;
}
if (ssn === "" || ssn > 4) {
error;
}
if (income === "") {
error;
}
if (code === "") {
error;
}
return true;
}
});
If you call the function in inline event onsubmit you should add return keyword to the function call in your form inline event like :
<form onsubmit='return validateForm()'>
But I think the main problem comes from the .value in your code it should be replaced by .val() since the value isn't an attribute of jQuery objects.
My suggestion is to attach the submit event in the JS code like the snippet below.
NOTE: The argument passed toremoveClass() and addClass() methods shouldn't contains dot . at the start.
$(function() {
$('form').on('submit', validateForm);
})
function validateForm() {
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
$(this).find("span.error_txt").removeClass("hidden").addClass("show");
if (first_name === "") {
return false;
}
if (last_name === "") {
return false;
}
alert('Form will be submited.');
return true;
}
.hidden {
display: none;
}
.show {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id='first_name'><br>
<input id='last_name'><br>
<button>Submit</button>
<span class="error_txt hidden">Error occurred check you form fields again.</span>
</form>
You need to return false in case the form is invalid, otherwise it will be submitted.
Related
Im still fairly new to JS and would like to be able to remove the event listener that stops the form submitting. I have tried multiple different solutions to do it in JS rather than jquery with no luck. The form currently does not submit, but i cannot get it to reverse should my 'if' conditions be false.
var element = document.querySelector('form');
element.addEventListener('submit', event => {
event.preventDefault();
});
function validateForm() {
var error = "";
if (document.getElementById("name").value == "") {
error += "<p>Name field required</p>"
}
if (document.getElementById("email").value == "") {
error += "<p>Email field required</p>"
}
if (document.getElementById("subject").value == "") {
error += "<p>Subject field required</p>"
}
if (document.getElementById("question").value == "") {
error += "<p>Question field required</p>"
}
if (error != "") {
document.getElementById("errorDiv").style.display = "block";
document.getElementById("errorDiv").innerHTML = "<b>There wer error(s) in the form, please complete all required fields</b>" + error;
} else {
var element = document.querySelector('form');
element.removeEventListener('submit', event => {
event.preventDefault();
});
}
}
<div id="errorDiv"></div>
<form id="contact_form" onsubmit="validateForm();">
<button type="submit"></button>
Thanks in advance if anybody can help.
I think you should return true/false from your validateForm() function to prevent/submit the form.
1. You have to return value from the function in the html markup:
<form id="contact_form" onsubmit="return validateForm();">
2. Return true/false from your validateForm() based on validation.
function validateForm() {
var error = "";
................
................
................
if (error != "") {
document.getElementById("errorDiv").style.display = "block";
document.getElementById("errorDiv").innerHTML = "<b>There wer error(s) in the form, please complete all required fields</b>" + error;
return false;
} else {
return true;
}
}
Does not required to prevent form submit so remove this code.
var element = document.querySelector('form');
element.addEventListener('submit', event => {
event.preventDefault();
});
I have following code to check if the inputs with the ids emailForm and nameForm are blank, this however isn't working when I test the form by leaving it blank.
function setInfo() {
if (document.getElementById("emailForm").value == null ||
document.getElementById("nameForm").value == null) {
alert("Please Fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
loaded();
}
}
Could someone help me with this, thanks!
Instead of checking for null specifically, you should check for falsy values. In some cases, the values for empty textboxes will be an empty string.
Replace this:
if (document.getElementById("emailForm").value == null || document.getElementById("nameForm").value == null) {
with this:
if (!document.getElementById("emailForm").value || !document.getElementById("nameForm").value) {
You shouldn't be checking whether the fields are null, you should be checking whether they content is an empty string (with .value == '').
This can be seen working in the following:
function setInfo() {
if (document.getElementById("emailForm").value == '' ||
document.getElementById("nameForm").value == '') {
console.log("Please fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
//loaded();
console.log("All sections filled in");
}
}
const button = document.getElementById('go');
button.addEventListener('click', function() {
setInfo();
});
<input id="emailForm" />
<input id="nameForm" />
<button id="go">Go</button>
Make sure you calling function setInfo()
function setInfo() {
// You can check Value.Length also or
if (document.getElementById("emailForm").value === "" ||
document.getElementById("nameForm").value === "") {
alert("Please Fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
loaded();
}
}
Try below solution:
function setInfo() {
var email=document.getElementById("emailForm").value;
var name=document.getElementById("nameForm").value;
if (email=='' || email==null || name=='' || name== null ) { // OR if (!email || !name)
alert("Please Fill in all sections");
return;
} else {
loaded();
}
}
You should check whether the string is empty or not instead of null. Try using the code below:
function setInfo() {
var a=document.getElementById("emailForm").value;
var b=document.getElementById("nameForm").value;
if (a == "" ||
b == "") {
alert("Please Fill in all sections");
} else {
email =
document.getElementById("emailForm").value;
name =
document.getElementById("nameForm").value;
alert("success alert");
}
}
I am having trouble submitting the below form.
For background, I'm trying to "submit" a form for a delivery, and I need to know a) their pickup address, b) their dropoff address, and c) their description. I created <p class="error"> fields if those <input>s are empty (as in "Please enter a description").
If I remove the 'return false;' the form submits no matter what, but if I keep the 'return false;' the jQuery works (i.e. - error message appears) but now the form NEVER submits. Thoughts?
Here's my main.js
var main = function() {
$('form').submit(function() {
var pickup = $('#pickup').val();
if(pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if(dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if(description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
return false;
});
};
$(document).ready(main);
var main = function () {
$('form').submit(function () {
var pickup = $('#pickup').val();
if (pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if (dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if (description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
// did not pass validation
if (pickup != "" || dropoff != "" || description != "") {
return false;
}
// passed validation, submit
return true;
});
};
$(document).ready(main);
I have form that I need to validate using JavaScript and I need to show all the messages at the same time. E.g if the first name and surename is missing for two messages to appear. I've got this working with the below code but the form is still being returned back to the server. P Lease see below:
function validateForm() {
var flag = true;
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "First name is required";
flag = false;
} else {
document.getElementById("fNameMessage").innerHTML = "";
}
var x = document.forms["myForm"]["surname_5"].value;
if (x == null || x == "") {
document.getElementById("sNameMessage").innerHTML = "Surename is required";
flag = false;
} else {
document.getElementById("sNameMessage").innerHTML = "";
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
flag = false;
} else {
document.getElementById("titleMessage").innerHTML = "";
}
return flag;
}
My form and event :
<form action=""method="post" accept-charset="UTF-8" name="myForm" onsubmit="return validateForm();">
My Button:
<input type="submit" class="button" name="submit" id="submit" value="Submit">
Your code:
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title")
... triggers an exception and you don't catch it:
Uncaught TypeError: Cannot read property 'options' of undefined
Thus JavaScript code stops running.
Since everyone seems to be providing jQuery answers and I didn't see anything in your orignal code that was jQuery-esque I'll assume you aren't using jQuery.
You should be using the event.preventDefault:
Sources:
https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.submit
document.getElementById("submit").addEventListener(
"click", validateForm, false
);
function validateForm(){
// We should not assume a valid form!
var formValid = false;
// All your validation code goes here
if(formValid){
document.forms["myform"].submit();
}
}
try something like
if(flag){
document.getElementById("submit").submit();
}
else{
$('#submit').click(function (e) {
e.preventDefault();
});
}
I have this javascript code (the function SHA-1 is located in an external file):
window.onload = validatePass;
function validatePass() {
var el = document.getElementById("oriPass");
var user_pass = el.value;
var hashed_pass = SHA1(user_pass);
var span = document.createElement("span");
el.parentNode.appendChild(span);
el.onblur = function doSomething() {
if(user_pass == null || user_pass == "") {
span.setAttribute('class','required');
span.innerHTML="this is a required field";
}
else {
if(hashed_pass != '7c4a8d09ca3762af61e59520943dc26494f8941b') {
span.setAttribute('class','required');
span.innerHTML="wrong password";
}
else {
span.setAttribute('class','required_ok');
span.innerHTML="valid password";
}
}
}
}
and this in html:
<form name="form" method="post" action="change_pass.php">
<div class="row">
<div class="col1">write your password:<span class="required">*</span></div>
<div class="col2">
<input type="password" name="original_pass" id="oriPass" />
</div>
</div>
</form>
For some reason, every time I test it I get the same output: "valid password", no matter if the field is empty, valid or invalid.
What am I doing wrong here?
move the var user_pass... and var hashed_pass... code inside the onblur function. Now the are assigned only onload and will never change. Also it might be better to use onchange instead of onblur.
window.onload = validatePass;
function validatePass() {
var el = document.getElementById("oriPass");
var span = document.createElement("span");
el.parentNode.appendChild(span);
el.onchange = function doSomething() {
var user_pass = el.value;
var hashed_pass = SHA1(user_pass);
if(user_pass == null || user_pass == "") {
span.setAttribute('class','required');
span.innerHTML="this is a required field";
}
else {
if(hashed_pass != '7c4a8d09ca3762af61e59520943dc26494f8941b') {
span.setAttribute('class','required');
span.innerHTML="wrong password";
}
else {
span.setAttribute('class','required_ok');
span.innerHTML="valid password";
}
}
}
}
You are setting the variable for password only on load. It never changes after that. You need to set it inside the onblur function.