Snippet of code not working - javascript

Below is a simplified snippet of code from a form validation script. It does not work...
When the form is submitted and the user has left "inputfield" empty, the first alert pops up. After the user has entered something in "inputfield", the second alert pops up when the user clicks submit.
Afterwards, the script should return false and continue validation. I need both alerts to be included in the same else if. What am I doing wrong? The alerts do not show and the form validation ignores this portion of code...
} else if (myform.inputfield.value=="") {
alert ('Please enter something in the text field!');
}
if (myform.inputfield.value!=="") {
alert ('Thank you for entering something in the field!');
return false;
}

Isn't it better to declare a flag and return the it as a result? take the following sample into account:
var validationResult = true;
...
} else if (myform.inputfield.value=="") {
validationResult = false;
alert ('Please enter something in the text field!');
}
if (myform.inputfield.value!=="") {
alert ('Thank you for entering something in the field!');
validationResult = false;
}
return validationResult;

I agree rather use document.getElementById, or jQuery $('#input1').val()
<script type="text/javascript">
function validate() {
if (document.getElementById('input1').value == "") {
alert('Please enter something in the text field!');
}
if (document.getElementById('input2') !== "") {
alert('Thank you for entering something in the field!');
return false;
}
}
</script>
</head>
<body>
<form onsubmit="return validate()">
<input id="input1" />
<input id="input2" />
<input type="submit" value="OK" />
</form>
</body>
You might have a return statement before the specified line of code?

Related

How to prevent refresh after clicking the alert OK button? Return false doesn't work here

I have a form to update a user's profile and I want to alert users when they leave the password field blank.
Currently, when a user leaves the password field blank and submits the form, the alert box will come up. But after clicking the OK button on the alert, the page refreshes and somehow the user updates his password to blank...
Here's my code:
$userProfileForm.on("submit", handleUpdateUserProfile);
async function handleUpdateUserProfile(e) {
e.preventDefault();
const updatedUser = {
name: $("#edit-user-name").val(),
password: $("#edit-user-password").val(),
};
if (!updatedUser.password) {
alert("Password can't be empty!");
// not working. It still refreshes the page and set the password to empty
return false;
} else {
currentUser = await currentUser.updateProfile(updatedUser);
saveUserCredentialsInLocalStorage();
return true;
}
}
I also tried e.preventDefault() but it's not working as well. Please tell me how I can prevent the page reload. Thanks!
Edit:
I changed return false to return true and it works...but I received a warning in the console saying [Violation] 'submit' handler took 1130ms jquery:5229
Could someone help me explain what's going on here?
Here's the new code:
$userProfileForm.on("submit", handleUpdateUserProfile);
async function handleUpdateUserProfile(e) {
e.preventDefault();
const updatedUser = {
name: $("#edit-user-name").val(),
password: $("#edit-user-password").val(),
};
if (!updatedUser.password) {
alert("Password can't be empty!");
// working now, the page doesn't refresh but receives a warning
return true;
} else {
currentUser = await currentUser.updateProfile(updatedUser);
saveUserCredentialsInLocalStorage();
// I have to use reload() to force the page upload
location.reload();
}
}
You do not need to return anything from that code. The e.preventDefault() should handle not submitting -
plain js version
document.getElementById("myForm").addEventListener("submit", asyncsubmit)
async function asyncsubmit(e) {
e.preventDefault();
if (e.target.querySelector("[name=q]").value === "") alert("Don't leave empty")
else console.log(e.target.id)
}
<form id="myForm" action="https://www.google.com/search">
<input type="text" name="q">
<input type="submit" value="search">
</form>
jQuery version
$("#myForm").on("submit", asyncsubmit)
async function asyncsubmit(e) {
e.preventDefault();
if ($(e.target).find("[name=q]").val() ==="") alert("Don't leave empty")
else console.log(e.target.id)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="myForm" action="https://www.google.com/search">
<input type="text" name="q">
<input type="submit" value="search">
</form>

display message on wrong password entry

I have a submit button which only works when "victory" is typed into the form. Now I am trying to work on an error message to display "wrong keyword entry" if the text entered into the form field isn't "victory". here is the code
<form name="input" action="index.html" method="post" onsubmit="return check();">
<input type="text" maxlength="7" autocomplete="off" name="" id="victory">
<br><input type="submit" class="bigbutton" value="NEXT">
</form>
<script>
function check(){
if(document.getElementById("victory").value == "victory")
return true;
else
return false;
}
If I were you I'd add an HTML element to stuff an error into. Then you can style it with CSS however you'd like.
<div id="error"></div>
Then your function would look something like this:
function check(){
if(document.getElementById("victory").value == "victory")
return true;
else
document.getElementById("error").innerHTML = "Wrong keyword entry."
return false;
}
You can simply add the alert in the else condition…
function check(){
if(document.getElementById("victory").value == "victory") {
return true;
}
else {
alert("wrong keyword entry");
return false;
}
}

Multiple onClicks in Submit Button

I have a submit button that redirects to another page if all the required fields are filled out.
<input type="submit" onclick="validateForm();redirect();" class="someClass" value="Submit" />
Right now when the button is clicked, it calls both functions. How do I get it to where it does not call redirect if validateForm returns false?
Here is the validateForm function if it helps:
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}
}
<input type="submit" onclick="validateForm(); return false;" class="someClass" value="Submit" />
Change the input to the code above. Also change your function to reflect the code below.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}else {
redirect();
}
}
Add a onclick handler, say validateAndRedirect:
function validateAndRedirect()
{
if(validateForm())
{
redirect();
}
else
{
return false;
}
}
Add this to the button:
<input...onclick="validateAndRedirect()" ... >
This function will call validate(). If validation fails, will return false. This false will prevent the submit action of the button. If validation passes, it will call redirect.
Make the first function call the next one and add this to your HTML :
<input> type=button onclick="validateForm(); return false;" </input>
Putting 'return false' will prevent redirection and will give time for your function to execute.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
} else
redirect();
}
Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:
<form onsubmit="validateForm()">
If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:
var button = document.getElementById("submit");
button.onclick = function validateForm() { /*same code as above..*/ };
Hope it helps!

Onclick event; If and Else

All right so I am doing a javascript code for a login type form and it will lead you to a new page. Here it is:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value=="username" && y.value=="password")
{
window.location="Example.php";
}
else
{
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
}
}
When ever I am hitting the submit button it takes me straight to the page instead of checking to see if it right. Please help!
Thank you in advanced! To let you know this is not a permanet login page!
The easy way to do this would be to use a button input:
<input type="button" value="Check" onclick = "submit1();" />
The alternative is to prevent this default behavior of a submit type input, by making the handler return false. Your HTML would look like this:
<input type="submit" value="Check" onclick = "return submit1();" />
Your function would need to be changed a well (considering the fact that you want it to not redirect). I am assuming you want to preserve data entered, so I am not going to use window.location to redirect. Instead, I am going to allow the form to be submitted:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value == "username" && y.value == "password") {
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
return false;
}
}
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")
{
window.location="Example.php"; /*opens the target page while Id & password matches*/
}
else
{
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
The event needs to cancel the default event and return false. This will prevent the form from submitting.
HOWEVER, it should be a non-issue if the form submits anyway, because JavaScript CANNOT be trusted and therefore you MUST validate all input server-side.
<form method="post" action="." id="myform">
<!-- form contents --->
</form>
<script type="text/javascript">
(function () {
var f = document.getElementById('myform'), // get your form element
x = document.getElementById('username'),
y = document.getElementById('password'),
handler;
handler = function (e) {
e.preventDefault(); // stop submit
if (x.value=='username' && y.value=='password') {
window.location = 'Example.php';
} else {
window.alert('The information...');
}
};
// listen to submit event
if ('addEventListener' in f) {
f.addEventListener('submit', handler, false);
} else { // handle also IE...
f.attachEvent('submit', function () {
handler(window.event);
});
}
}());
</script>
anyway it looks like you're trying to check login/password from JS what is not greatest idea (anyone can just look into source and read it)

stop form during submission if it validates incorrectly

I am trying to use JavaScript to validate forms but if the form doesn't validate, I don't want the form to be sent to the "action" page.
The validator:
<script>
function formSubmit()
{
document.getElementById("signup_form").submit();
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
The form itself:
<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">
But all this does is if the tname field empty, it will return an alert but as soon as the user hits ok, the form then redirects to some_file.php. What have I missed here?
The submit button:
Signup
So what have I missed? How do I avoid this in the future?
You have the wrong execution of statememts. You are submitting the form before validating. Move this statement below the if statement
document.getElementById("signup_form").submit();
further to this. you are calling formSubmit() at two places, form tag and a tag doing it once is fine.
UPDATED CODE:
<html>
<head>
<title></title>
<script>
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
document.getElementById("signup_form").submit();
}
</script>
</head>
<body>
<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">
<input type="text" name="tname" />
Signup
</body>
</html>
DEMO
Try this:
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x=="")
{
alert("First name must be filled out");
return false;
}
return true;
}
*Changes made to your code: *
- There is no need for formSubmit to try to submit the form! Just perform the validation checks and return true if you want the submission to proceed or false otherwise.
Also you do not need to check for the x == null case. If the textbox is empty, its value will be "".
What might be needed though is a check that x does not just contain spaces. If you do not care about supporting older browsers you can use the new Javascript trim function. If you care about backwards compatibility, either try one of the many javascript libraries that offer trim or the following:
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value.replace(/^\s+|\s+$/g, '');
if (x=="")
{
alert("First name must be filled out");
return false;
}
return true;
}
If I just wanted to avoid submitting spaces I would have left the var x= bit as it was and added the replace in the check making it if(x.replace(/\s/g, '') == ""). However, I also want to trim the input so that if the user enters " user1" or "user1 " the form will send "user1".
You can see the three different versions versions working here:
http://jsfiddle.net/9LPfb/2/
http://jsfiddle.net/9LPfb/3/
http://jsfiddle.net/9LPfb/6/
you have problem with your program flow .
do validation before the submitting form.
there is no use of validating after submitting, i think you have mistakenly made it.
just submit after validation.
try:
function formSubmit() {
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else {
return true;
}
}
You already had all the code. It was becos of wrong execution.
<script>
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (!x){
alert("First name must be filled out");
return false;
}
return true;
}
</script>
<form action="some_file.php" method="post" id="signup_form" name="signup_form">
Signup
in your function just remove this line
document.getElementById("signup_form").submit();
and add it after the if condition
or rewrite the function like the one below
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}else
return true;
}
Contact Form
function empty() {
var x,y;
x = document.forms["ff"]"name"].value;
y = document.forms["ff"]["surname"].value;
if(x=="" ||x==null){
alert("Enter your name");
return false;
}else if(y==""){
alert("Enter your surname");
return false;
}else{
alert('Data is sending');
return true;
}
};
In the html:
<form method="POST" action="formdata.php" name="ff"onsubmit="return empty()">
<table>
<tr>
<td>Enter Your Name : <input type="text" name="name" maxlength="30" size="40" id="na" ></td>
</tr>
<tr>
<td>Enter Your Surname : <input type="text" name="surname" maxlength="30" size="40" id="sna"></td>
</tr>
<tr>
<td>
<input type="submit" name="formsubmit" value="submit" >
</td>
</tr>
</table>
</form>

Categories

Resources