That is the thing.
My head:
<script language="JavaScript">
function checkIt(){
var pass = document.form1.value;
if (pass == "1234")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
window.onload = checkIt();
</script>
My body:
<form action="#" method="post" id="form1" onsubmit="checkIt();">
<input type="password" id="sn" name="sn" placeholder="Enter Your Password">
<img src="ok.gif" onclick="submit();" style="cursor: pointer;">
</form>
Can anybody tell me what I am doing wrong? It is not working. I need it to be able to compare entered value named sn, with var pass.
I am noob and not a native speaker, so stay calm, please:)
Fix your script
// to get the input value
var pass = document.getElementById("sn").value;
And on your form you have to return the result of the function
onsubmit="return checkIt();"
Also remove window.onload = checkIt(); that will validate the form before you enter any value
try the following:
Javascript
<script language="JavaScript">
function checkIt(){
var pass = document.getElementById("sn").value;
if (pass == "1234")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
</script>
HTML
<form action="#" method="post" id="form1" onsubmit="return checkIt();">
<input type="password" id="sn" name="sn" placeholder="Enter Your Password">
<img src="ok.gif" onclick="document.getElementById("form1").submit();" style="cursor: pointer;">
</form>
Try var pass = document.getElementById('sn').value;
onclick="form1.submit()" and onsubmit="return checkIt()"
You are calling the function, not assigning it
window.onload = checkIt();
Needs to be
window.onload = checkIt;
But do you really want to run the validation when the page loads? You probably do not need this line at all. Delete it!
You are not cancelling the submit event. Your function returns true or false, but you are not handling it.
<form action="#" method="post" id="form1" onsubmit="checkIt();">
Your form tag needs to be
<form action="#" method="post" id="form1" onsubmit="return checkIt();">
notice the return statement. That will cancel the submission.
What is submit()? The page is probably throwing an error which you would be able to see in the console. You need to tell it what to submit. That means referencing a form.
<img src="ok.gif" onclick="submit();" style="cursor: pointer;">
There is no method called submit() in your code. Maybe you want to call the form submission.
<img src="ok.gif" onclick="doucment.form1.submit();" style="cursor: pointer;">
You would probably be better off using input with type="image" to submit the form.
<input type="image" src="ok.gif" />
Using the input means no JavaScript is needed to submit the form. So remove the image tag and add the input element!
And finally you are reading the value of the form, not the input
var pass = document.form1.value;
You want the input!
var pass = document.form1.sn.value;
And it makes no sense why 1234 would fail, but all other things pass. Don't you have the logic wrong?
You need to learn how to debug, use the browser's console and learn to use console.log() to see the data. Set break points and walk through the code so you can inspect what is going on. JavaScript 101.
Related
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.
<form id="loginForm">
<p id="usernameLabel">Username:</p>
<input type="text" name="username" id="username" placeholder="username"/><br>
<p id="passwordLabel">Password: </p>
<input type="password" name="password" id="password" placeholder="password"/><br>
<input id="loginButton" type="submit" value="Login!" onsubmit="validateForm()">
</form>
<p id="loginMessage">Please Login!</p>
<script type="text/javascript">
function validateForm() {
var un = document.loginForm.username.value;
var pw = document.loginForm.password.value;
var username = "MitchWardle";
var password = "123abc456";
if ((un == username) && (pw == password)) {
window.location = "content.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
I have created a little login form on Javascript and I want it to navigate to Content.html when username and password are correct but when I click my Login button it just removes the text from the text box's, can anybody see whats wrong?
you need to return false to prevent default action of submitting the form , page gets refresh andyou loss your data, you can set type of submit button to
type="button"
or can change onsubmit to
onclick="validateForm(); return false; "
Just a couple things are off, but it's almost there:
The onsubmit handler is used at the form level. Either move the onsubmit to the <form> element or change it to an onclick event for the <input> element.
In order to reference the text fields the way you are, the <form> element also needs a name attribute. i.e. name="loginForm"
Do this:
Remove onsubmit from button add it to form.
Change id of form to name.
In the onsubmit of form append return false;.
Remove return false; from the if statements.
Change document.loginForm line to this:
document.forms['loginForm'].elements['username'].value //username/password depends.
Hope it works.
I have had the same problem as you before, and I solved it by changing the submit button to <input type="button" onclick="login();" />, and everything worked. However, the user then cannot submit the form with enter key (because there's no submit button in the form).
I have some javascipt code here that validates a user form. When the user inputs the correct answer it tells them and gives them the link to the next question. At least, that's what it is supposed to do. When i click the form it reloads the page but it should not because i added return false.
the div tra holds 35
and the div usermsg is the user inputted value.
<script>
$("#submit").click(function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6<>rightanswer)
{
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else
{
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
</script>
Any ideas why this is not working?
It should be
if (clientmsg6 != rightanswer)
not
if (clientmsg6<>rightanswer)
To prevent a form submission, you need to return false on the form itself instead of on the submit button. Your code should become:
HTML
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="submit" value="Submit" />
</form>
JS (please note the line where you have clientmsg6, you have a syntax error)
$("#myform").on('submit', function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6 != rightanswer) { //This line was also wrong, should be != instead of <>
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else {
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
Alternatively, you can keep your existing code by changing your submit button to be just a plain old button, but you will lose the extra functionality of the user being able to hit the enter key and performing the same action.
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="button" value="Submit" />
</form>
Instead of using .html(), try using .text()
if #submit is a link tag otherwise use the form ID and the submit event
$("#submit").click(function(e){
e.preventDefault()
...
...
...
});
You need to attach handlers once the document has finished loading.
Wrap your script in the following
<script>
$(function() {
// script
});
</script>