I'm having trouble displaying an error message in my form using JavaScript.
Here is part of my form and the input field that I'm trying to access with JS. I'd like to add the error message underneath inside the span tags.
<form name="subform" id="subform" action="submit.php" onsubmit="return checkForBlank()" method="POST" enctype="multipart/form-data">
<div class="md-form">
<input type="text" id="subcim" name="subcim" class="form-control">
<label for="subcim" class="">Title</label>
</div>
<span class="error_form" id="subcim_error_message"></span>
Here is my JavaScript code:
function checkForBlank() {
if(document.geElementById("subcim").value == "") {
document.getElementById("subcim_error_message").textContent="You must add a title!";
return false;
}
}
So basically the error message should appear when the input field is left empty. But it's not shown.
Any help is appreciated.
Try document.getElementById("subcim_error_message").innerHTML="You must add a title!";
Related
I'm making two forms with html and javascript, one for "log in" and one for "register". Im using javascript to check that the inputs on the forms are valid. Im running into an issue where the "email" field on the "log in" form is being validated properly, but the "email" field on my "register" form is not, although they are using nearly identical event listeners to validate the inputs.
this is a condensed version of the code that I am using to do this
<html>
<form class="forms" id="login-form" onsubmit="return false" novalidate>
<h1>Log In</h1>
<div class="form-div">
<label for="email">Your Email:</label>
<input type="email" id="email" name="email" required>
<span class="error"></span>
</div>
<button class="wide-buttons" type="submit">Log In</button>
<p onclick="toggleForms()">Need an account? Click here to sign up!</p>
</form>
<form class="forms" id="register-form" onsubmit="return false" novalidate>
<h1>Register</h1>
<div class="form-div">
<label for="email">Your Email:</label>
<input type="email" id="register-email" name="register-email" required>
<span class="error"></span>
</div>
<button class="wide-buttons" type="submit" onclick="validateRegister()">Sign Up</button>
<p onclick="toggleForms()">Already have an account? Click here to log in!</p>
</form>
<script>
const loginForm = document.getElementById("login-form");
const emailError = document.querySelector("#email + span.error");
const registerForm = document.getElementById('register-form');
const regEmailError = document.querySelector("#register-email + span.error");
loginForm.addEventListener("submit", (event) => {
if (!email.validity.valid) {
emailError.textContent = "You must enter a valid email address";
}
});
registerForm.addEventListener("submit", (event) => {
if (!email.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
});
</script>
Im using event listeners for a "submit" event on each form and the one for "loginForm" Is working the way that I intend it to, but the one for "registerForm" is showing my error message when the email is a valid email or anything else is put into the email field. Im stumped by this considering the listeners are practically identical. I don't need to actually submit the form to anything, I'm just trying to learn how some basic form validation works. This code is a snippet of everything else that I have written, but my passwords, checkboxes, etc. are working fine for me. I just need to know how to get the "registerForm" event listener to work the same way that the "loginForm" one is.
edit: Im aware of the onclick="validateRegister()" on the register form- I have removed this in my code and I am still having the issue.
Any help, constructive criticism, or funny jokes are appreciated.
thanks.
It looks like you are trying to check the validity of the email input element on both forms, but you should be checking the validity of the register-email input element on the registerForm event listener.
Change:
if (!email.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
To:
const registerEmail = document.getElementById('register-email');
if (!registerEmail.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
and it should be ok
Edit1: Ofc you can declare registerEmail above event listener
I'm having issues with form submit - somehow when user has not clicked submit button, upon refresh of the page, the validation is ran and the error message is shown on the page.
Anyone knows why onsubmit doesnt work here, and how do i only show the error on form submit?
HTML:
<form action="#" method="POST" name="signupForm" class="ggForm" onsubmit="return validateSignupForm()">
<div class="email">
<label for="emailBox">Email*:</label>
<input type="email" name="custEmail" id="emailBox" placeholder="john.doe#gmail.com" required
pattern="^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" title="(The email entered is invalid)">
</div>
<!-- submit button below -->
<div>
<input type="submit" value="Submit Form">
</div>
<p id="potentialErrors"></p>
</form>
JS:
window.onload = init;
function init() {
document.forms["signupForm"].onsubmit = validateSignupForm();
}
function validateSignupForm() {
console.log("ran");
var errMsg = "";
var email = document.forms["signupForm"]["custEmail"].value;
if (email == "") {
errMsg += "<br>Email must be filled out";
}
// when there's errors in any field, put as message below submit button
if (errMsg != "") {
document.getElementById("potentialErrors").innerHTML = errMsg;
//change the error message css
$("p#potentialErrors").css("height","50");
$("p#potentialErrors").attr("width","500");
$("p#potentialErrors").css("font-weight","bold");
$("p#potentialErrors").css("color","red");
return false;
}
return true;
}
Edit FYI: i have edited the above code into this codepen, it is working now:
https://codepen.io/vadevalor/pen/VwepxdY
need to add jquery library,
need to remove html validation
as per comments for this question, need to remove () in the js function
You need to add onsubmit in the form event.preventDefault();, next add jquery library to you code.
So:
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<form action="#" method="POST" name="signupForm" class="ggForm" onsubmit="event.preventDefault(); return validateSignupForm()">
Here is the code;
<form data-test="loginForm-container" novalidate="" method="POST" enctype="multipart/form-data">
<div class="css-o5d3v1 e1ovefus2">
<div data-test="guestForm-email-wrapper" class="e1ovefus1 css-yjv4po e1eu3ser1">
<div class="css-gg4vpm e1eu3ser4">
<label for="guestForm-email" id="guestForm-email-label" data-test="input-label" class="css-1k1vx4d e1eu3ser5">Email Address*</label>
</div>
<div class="css-1tpy6sb e1eu3ser7">
<input data-test="guestForm-email" aria-invalid="true" aria-required="true" id="guestForm-email" type="email" name="email" aria-labelledby="guestForm-email-label" class="css-15uq4zo e1eu3ser9" value="" aria-describedby="guestForm-email-error">
</div><span data-test="input-error" id="guestForm-email-error" role="alert" class="css-mf5akt e1eu3ser0">Please enter email address</span></div>
</div>
<button type="submit" data-test="guestForm-submitButton" class="e1ovefus0 css-1wqqz58 e1y6awi20"><span>Continue as Guest</span></button>
I tried doing;
$("#guestForm-email").value = "test#gmail.com"
but when submit it deletes the text in textfield.
I just need to learn how to validate it in JQUERY.
Can anyone help?
Thanks.
Not sure what exactly this has to do with validation, but this is not how you set a value to a form element in jQuery:
$("#guestForm-email").value = "test#gmail.com"
This is:
$("#guestForm-email").val("test#gmail.com")
First of all you cant write this as
$("#guestForm-email").value = "test#gmail.com"
this is the correct syntax
$("#guestForm-email").val("test#gmail.com")
and try to do this in function that return true if the data is valid an call it in
<form onSubmit="return validate()">
I guess what you are trying to do is to validate the e-mail sent on the input text field using jQuery. You can use a reg expression for this within your button's click event handler like so:
$(document).ready(function() {
$("button[type=submit]").click(function() {
if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($("#guestForm-email").value)) {
return $("#guestForm-email").value;
} else {
alert("Invalid E-mail");
}
}
}
I think you want to append text inside input:
$("#guestForm-email").val($("#guestForm-email").val()+"test#gmail.com")
Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.
I'm making a issue reporting form with categories and sub categories. The form also requires the user to add their e-mail address (from a list). The list has the data-live-search = true to give them the possibility to search for it in the list.
The form submits if you first start to type in the search field for the e-mail and then selects it, but if you don't write in the search bar and just select it from the list (without typing anything), the form won't submit... This is what the form looks like (a simplified version, but still not working):
<form role="form" name="form" id="form" action="file.php" method="post">
<!-- AUTHOR NAME -->
<div class="form-group" id="form-group-author-name">
<label class="sr-only" for="author-name">Author's name</label>
<input type="text" name="author-name" id="form-author-name" placeholder="Author's name" class="form-control" required>
</div>
<!-- AUTHOR E-MAIL -->
<div class="form-group" id="form-group-author-email">
<select class="selectpicker" name="author-email" id="form-author-email" data-width="100%" title="Author's e-mail" data-live-search="true" required>
<option>email1#example.com</option>
<option>email2#example.com</option>
<option>email3#example.com</option>
<option>email4#example.com</option>
<option>email5#example.com</option>
</select>
<p class="help-block">Search for your e-mail.</p>
</div>
<button type="submit" class="btn">Submit</button>
</form>
I've also tried to add an event listener to the select field and use $("#" + "form-author-email").selectpicker('refresh'); and document.getElementById("form-author-email").value = $("#" + "form-author-email").val(); in case it was because of the field not updateing, but that wasn't working either.
If I use console.log($("#" + "form-author-email").val()); I still get the value selected, so I don't understand what the problem is.
I've figured out the problem. I've added a jQuery validation function (for all input fields) that used e.preventDefault(); and added a error styling-class if the input was empty, which it would always be if they didn't type anything into the search bar. I've add the code below in case anybody has done the same thing:
jQuery(document).ready(function() {
$('.form input[type="text"]').on('focus', function() {
$(this).removeClass('error');
});
$('.form').on('submit', function(e) {
$(this).find('input[type="text"]').each(function(){
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('error');
}
else {
$(this).removeClass('error');
}
});
});
});