How to check if function returns true - javascript

I have a web form that submits if my function validate form returns true in that function i wrote an if statement that if another function called usernamecheck returns true then return the validateform function true. I dont want the form to submit unless you click the button to check the username. I know i didnt write this the best way i hope you understand
<!-- Signup Form -->
<form name='signup' action="subscription.php" onsubmit="return validateForm();" method="post" >
<input type="text" id="signupUsername" name="signupusername" placeholder="Business Name" tabindex=1 required>
<input type="password" id="signupPassword" placeholder="Password" name="signuppassword" tabindex=2 required> <br>
<input type="text" id="ownerName" placeholder="Owner's Name" name="ownername" tabindex=3 required>
<input type="email" id="signupEmail" placeholder="Email" name="signupemail" tabindex=4 required>
<input type="tel" id="signupphoneNumber" placeholder="Phone Number" name="signupphonenumber" tabindex=5 required>
<input type="image" id="signupSubmit" src="images/signupBtn.jpg">
<input type="text" id="city" placeholder="City" name="city" tabindex=6>
<input type="text" id="state" placeholder="State" name="state" tabindex=7>
This is the button that you click to check your username if it exists
<input type="button" id='check' value="Check It">
//
</form>
<script type="text/javascript">
Below there is the function where if you click the button above it checks the function usernamecheck
$(function() {
$( "#check" ).click(function() {
return usernamecheck();
});
});
Below is the validateForm function where if usernamecheck returns true it returns true as well and submits the form
function validateForm()
{
if(usernamecheck() && $("#signupUsername").val().length < 4) {
return true;
}
}
function usernamecheck() {
$.post( "checkusername.php", { username: $("#signupUsername").val() })
.done(function( data ) {
result = JSON.parse(data);
if(result["status"]== "Username is taken")
{
alert("username is taken");
return false;
}
else if(result["status"]== "Username is Available") {
alert("username is Available");
return true;
}
else {
alert('You did not check the username');
}
});
}
</script>
<!-- Map Logo -->
<img src='images/map.jpg' id="map" class='menuitems'>
<!-- About Us Logo -->
<img src='images/aboutus.jpg' id="aboutus" class='menuitems'>
<!-- People Logo -->
<img src='images/people.jpg' id="people" class='menuitems'>
</div>
</div>
</div>
</body>
</html>

Related

Jquery Validation and Messages

I'm trying to get an error message to show when my fields are missing input. Once both are filled in I want a success message to show in place of #error.
Not sure why I'm not getting any message currently.
$("input[type='button']").click(function() {
$("form").validate({
rules: {
username: "required"
},
messages: {
username: "please enter a name"
}
});
alert("Submitted");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<form>
<p>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</p>
<p>
<label for="pw">Password:</label>
<input type="password" name="pw" id="pw">
</p>
<p>
<input type="button" value="Submit">
</p>
<!-- placeholder for response if form data is correct/incorrect -->
<p id="error"></p>
</form>
What about this ?
$("input[type='button']").click(function() {
if($("#username").val()==""){
$("#error").html("Please enter a name");
return;
}
if($("#pw").val()==""){
$("#error").html("Password required");
return;
}
alert("Submitted");
});

Validating login form using javascript

I'm relatively new to HTML and JS and I've been trying to create a simple login page that on entering valid credentials redirects to index.html page. But no matter what I enter it always redirects to the index.html page. Here's the HTML code for the login page
<form role="form" action="index.html" name="formlogin" method="post" class="login-form" onsubmit="check_info()">
<div class="form-group">
<label class="sr-only" for="form-username">Username</label>
<input type="text" name="form-username" placeholder="Username..." class="form-username form-control" id="form-username">
</div>
<div class="form-group">
<label class="sr-only" for="form-password">Password</label>
<input type="password" name="form-password" placeholder="Password..." class="form-password form-control" id="form-password">
</div>
<button type="submit" class="btn" value="submit">Sign in!</button>
</form>
Here's the javascript
<script type="text/javascript">
function check_info()
{
var myform = document.formlogin;
if(myform.form-username.value == "test")
{
if(myform.form-password.value == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
P.S: I'm using a bootstrap login template.
Html:
onsubmit="return check_info()"
Javascript:
function check_info()
{
var user = document.getElementById("form-username").value;
var pass = document.getElementById("form-password").value;
if(user == "test")
{
if(pass == "123")
{
return true;
}
}
return false;
}
You can use required parameter like this:
<input type="text" name="form-username" placeholder="Username..." class="form-username form-control" id="form-username" required>

Execute PHP Submit button Only if Javascript is true

I am trying to execute the mysql query using PHP form. Below is the form
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="signup.css" type="text/css">
<script type="text/javascript" src="form_val.js"></script>
<title>Untitled Document</title>
</head>
<body bgcolor="#0ca3d2">
<div align="right">
<h2>Go back</h2>
</div>
<div class="form-style-10">
<h1>Sign Up Now!<span>Sign up and tell us what you think of the site!</span></h1>
<form action="#" method="post" name="myForm" onSubmit="CheckTerms()">
<div class="section"><span>1</span>First Name & Address</div>
<div class="inner-wrap">
<input type="text" name="First_Name" placeholder="Enter First Name" id="fname">
<label id="error" style="color:red"></label>
<input type="text" name="Last_Name" placeholder="Enter last Name"/>
<label id="error_l" style="color:red"></label>
<select name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="section"><span>2</span>Email </div>
<div class="inner-wrap">
<input type="text" name="Email_i" placeholder="enter email here" id="e_mail" />
<label id="error_e" style="color:red"></label>
<button type="button" name="validate" onclick="loadDoc(this.value)">Validate</button>
<div id="check"></div></div>
<div class="section"><span>3</span>Passwords</div>
<div class="inner-wrap">
<input type="password" name="pass" placeholder="Must be 6 to 15 characters" id="Pass" onBlur="PassCheck()" />
<label id="error_p" style="color:red"></label>
<input type="password" name="repass" placeholder="Retype Password" id="RePass"/>
<label id="error_rp" style="color:red"></label>
<span class="privacy-policy">
<input type="checkbox" name="terms" value="value1" id="check_box">Agree to Terms and Conditions
</span>
<input type="submit" name="signup" value="Register" id="sub_button">
<label id="error_lable" style="color:red"></label>
</div>
</form>
</div>
</body>
I have the below form validation in Javascript,
function CheckTerms(){
var letter = /^[a-zA-Z ]*$/;
if(document.myForm.First_Name.value.match(letter) && document.myForm.First_Name.value =="")
{
document.getElementById("error").innerHTML = "* Please Provide First Name";
document.myForm.First_Name.focus();
return false;
}
if(document.myForm.Last_Name.value.match(letter) && document.myForm.Last_Name.value =="" )
{
document.getElementById("error_l").innerHTML = "* Please provide your Last name!";
document.myForm.Last_Name.focus() ;
return false;
}
var email =/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if(document.myForm.Email_i.value.match(email) && document.myForm.Email_i.value=="")
{
document.getElementById("error_e").innerHTML = "* Please provide your EMAIL!";
document.myForm.Email_i.focus() ;
return false;
}
var min = 6;
var max = 15;
if(document.myForm.pass.value.length < min || document.myForm.pass.value.length > max)
{
document.getElementById("error_p").innerHTML = "Password Should be betweeen 6 to 15 characters";
document.myForm.pass.focus() ;
return false;
}
var pass = document.getElementById("Pass").value;
var re = document.getElementById("RePass").value;
if(pass != re)
{
document.getElementById("error_rp").innerHTML = "Password do not match";
return false;
}
if(document.getElementById("check_box").checked == false)
{
document.getElementById("error_lable").innerHTML = "Please Check";
return false;
}}
<?php
session_start();
include "config.php";
if(isset($_POST['signup']))
{
// my logic here
}
?>
but the problem is, even the javascript returns the error, clicking the submit button , executes PHP script resulting the data entry into database. I want to stop form submission if any of the javascript error exists.
You are not returning the boolean in the event even though you are doing it in the function. onSubmit receives true by default and submits it.
Change
onsubmit="CheckTerms()"
to
onsubmit="return CheckTerms()"

Redirecting a form with multiple submit inputs

I have a form which has 3 separate input with a type of "submit".
The first two inputs output a message once they are clicked, but the final one is supposed to redirect to another page however it is not doing this. I think this is because the form is submitting and refreshing the page before it gets to the JavaScript for redirection.
Here is my code:
FORM.php
<form class="form" id="form" method="POST" enctype="application/x-www-form-urlencoded">
<br>
<input type="email" name="email" id="email" maxlength="80" value="<?php echo $email ?>" placeholder="Enter Your Email" /><br /><br>
<input id="button4" type="submit" value="Get Security Question" name="submit2" style="cursor:pointer;"/><br>
<br><input type="password" name="securitya"id="securitya" maxlength="20" value="<?php echo $securitya ?>" placeholder="Enter Your Security Answer" /> <br />
<br>
<input id="button3"type="submit" value="Check Answer" name="submit" style="cursor:pointer;"/>
<br>
<br><input type="password" name="newpassword" id="newpassword" maxlength="20" placeholder="Enter Your New Password" /> <br />
<br><input type="password" name="confirmpassword" id="confirmpassword" maxlength="20" placeholder="Re-Enter Your New Password" /> <br />
<br>
<input id="button2" type="submit" value="Change Password" disabled="disabled" name="submit" style="cursor:pointer;"/>
JavaScript
jQuery(function(){
$("#button2").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#newpassword").val();
var checkVal = $("#confirmpassword").val();
if (passwordVal == '') {
$("#newpassword").after('<span class="error" >Please enter a password.</span>');
hasError = true;
} else if (checkVal == '') {
$("#confirmpassword").after('<span class="error">Please re-enter your password.</span>');
hasError = true;
} else if (passwordVal != checkVal ) {
$("#confirmpassword").after('<span id = "pass" class="error">Passwords do not match.</span>');
hasError = true;
}
if(hasError == true) { return false; }
else {
$("#button2").after('<span class="error">Passwords accepted.</span>');
window.location.href='adminsignin.php';
}
});
});
What is weird about this is the message 'Passwords accepted' appears on screen for a split second, but there is no redirection to 'adminsignin.php'
Can anyone help?
In your javascript, pass the event into the click handler, and preventDefault().
$("#butotn2").click(function(e) {
e.preventDefault();
...
}
the submit button has default behavior, so you'll want to prevent its default behavior so that you can perform your operations and then redirect with your window.location.href.
please try changing to document.location = 'your URL';

basic form validation not working

This simple form validation is not working and it's irritating me. Please let me know what is the problem. I have been trying to find a bug for almost two hours but can't find it. Please help me.
Take a look at code:
function validate()
{
if( $("#full_name").val() == "" )
{
alert( "Please provide your name!" );
$("#full_name").focus() ;
return false;
}
if( $("#email").val() == "")
{
alert( "Please provide your Email!" );
$("#email").focus() ;
return false;
}
if( $("#message").val() == "" )
{
alert( "Please Enter Message" );
return false;
}
return( true );
}
<div class="form">
<h2> Contact Us </h2>
<form name="c_form" action="#" method="post" onsubmit="return(validate());">
<div class="input">
<input type="text" name="full_name" id="full_name" placeholder="Full Name">
</div>
<div class="input">
<input type="text" name="email" id="email" placeholder="Email Address">
</div>
<div class="input textarea">
<textarea id="message" name="message" placeholder="Enter Message Here"></textarea>
</div>
<div class="input button">
<button id="button"> Send </button>
</div>
</form>
</div>
Why not using HTML5's native "required" attribute? Nowadays, most browsers will happily interpret it without problems. If you want to support older browsers, just use a library like h5validate, but (please) keep your html clean.
Take a look on the same form using those attributes. No JS, no DIV containers, just plain native Html:
input, textarea {
display:block;
margin-bottom: 5px;
}
<h2> Contact us without JS </h2>
<form name="c_form" action="#" method="post">
<input type="text" name="full_name" placeholder="Full Name" required>
<input type="email" name="email" placeholder="Email Address" required>
<textarea name="message" placeholder="Enter Message Here" required></textarea>
<button type="submit"> Send </button>
</form>
I made a few changes and it works. The following snippet:
Include jQuery.
Add all the contents inside $(function () {}).
function validate ()
{
if( $("#full_name").val() == "" )
{
alert( "Please provide your name!" );
$("#full_name").focus() ;
return false;
}
if( $("#email").val() == "")
{
alert( "Please provide your Email!" );
$("#email").focus() ;
return false;
}
if( $("#message").val() == "" )
{
alert( "Please Enter Message" );
return false;
}
return( true );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="form">
<h2> Contact Us </h2>
<form name="c_form" action="#" method="post" onsubmit="return(validate());">
<div class="input">
<input type="text" name="full_name" id="full_name" placeholder="Full Name">
</div>
<div class="input">
<input type="text" name="email" id="email" placeholder="Email Address">
</div>
<div class="input textarea">
<textarea id="message" name="message" placeholder="Enter Message Here"></textarea>
</div>
<div class="input button">
<button id="button"> Send </button>
</div>
</form>
</div>
I added an id of "c_form" to your html and removed the onsubmit property and used the following javascript code, which seemed to work. The key is calling ev.preventDefault();
$(document).ready(function () {
$("#c_form").submit(validate);
});
function validate(ev)
{
if( $("#full_name").val() == "" )
{
alert( "Please provide your name!" );
$("#full_name").focus() ;
ev.preventDefault();
return false;
}
if( $("#email").val() == "")
{
alert( "Please provide your Email!" );
$("#email").focus() ;
ev.preventDefault();
return false;
}
if( $("#message").val() == "" )
{
alert( "Please Enter Message" );
ev.preventDefault();
return false;
}
return true;
}

Categories

Resources