Stopping action if requirements are not met - javascript

I want to check the validation of two text boxs if either one is empty. It showed show an error as an innerHTML and if they are both filled in. It will then continue to action. Here is my code:
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
this does set the innerHTML but still continues with the action. How can I stop it from continuing?
Thank you!

You should check the value of text box,
Change the code to
function go()
{
var toCheck = document.getElementById('myAnchor').value;
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}

add the onsubmit on the form:
<form onsubmit="return true;">
...
</form>
if the return is false it will stop from submitting an opposite scenario if it's true. you could also call your functions on that attribute and do the same thing then if it doesn't fit the condition it will stop from submitting your form and do the other process you desire to happen.

Textfields use the value attribute.
document.getElementById('myAnchor').value = 'Fred Flinstone';
An empty textfield would have a value of "".
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
Here's a working example.
<!DOCTYPE html>
<html>
<body>
<form name="form" action="data.php">
<label style="float:left">
<font face="Comic Sans MS">* username &nbsp
</label></font>
<input type="text" id='textfield' name="name" size="40" style="float: left;">
<label id='myAnchor' style="display: inline; padding-left: 20px;"></label> <br/> <br/>
<label style="float:left"><font face="Comic Sans MS">* password &nbsp</label></font>
<input type="text" name="pwd" size="40" style="float: left;">
<label id="myAnchor2" style="display: inline; padding-left: 20px;">
</label> <br/> </p> <input type="button" value="LogIn" onClick="return go();"> </form>
</body>
<script>
function go()
{
var toCheck = document.getElementById('textfield');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
</script>
</html>

In your question you said that
I want to check the validation of two text boxs
In that case you should be checking the value of textboxes, not the myAnchor.
I would change your html code like this:
<input type="text" name="name" id="name" size="40" style="float: left;">
<input type="text" name="pwd" id="pwd" size="40" style="float: left;">
<input type="submit" value="LogIn" onSubmit="go();">
adding id to the input boxes
then change the onClick event to onSubmit. that way you can perform javascript validation in the function, then submit the form if all goes well, otherwise display the error.
Then your script will be like...
function go() {
var name = document.getElementById('name').value,
pwd = document.getElementById('pwd').value;
if (name != '' && pwd != '') {
document.forms["form"].submit();
}
else {
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}

Related

How to disable button until input field has a value using AngularJS

I know nothing about Angular but I was asked to create a validation for the new google map input. All I want to do is have the #lugar_continuar button stay disabled until the input #ciudad is filled in, but the button isn't disabled for some reason.
index.php, input to validate
<div class="">
<input id="ciudad" name="ciudad" class="ciudad" type="text"
placeholder="Ciudad" value="" required ng-model="ciudadSet">
<div id="map"></div>
<input type="hidden" id="distance" size="31" value="31">
</div>
Input type button that should stay disabled
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && ciudadSet" ng-click="from_precio = true" >
Using ng-model doesn't work. I also tried with JS, in main.js:
var ReservasApp = angular.module('Reservas',['rzModule']);
ReservasApp.controller('ReservasController',function($scope){
$scope.ciudad = "";
$scope.validacionCiudad = function() {
var disabled = false;
if( $scope.ciudad != null && $scope.ciudad != "" )
{
disabled = false;
}
else
{
disabled = true;
}
}
}
index.php
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && validacionCiudad()" ng-click="from_precio = true" >
I also tried using only JS:
var validacionCiudad = function() {
var ciudad = document.getElementById('ciudad');
var btn = document.getElementById('lugar_continuar');
if (ciudad.value == "") {
btn.setAttribute("disabled", "disabled");
} else {
btn.removeAttribute("disabled");
}
}
validacionCiudad();
I have tried many ways to achieve this but nothing is working!
you can try this: ng-disabled = "ciudadSet == ''", since ng-disabled is valid when the expression equals true. If you must call function validacionCiudad to judge this, you have to return bool value in your function. May this will help.
Change $scope.ciudad ="" to $scope.ciudad = undefined;
change your ng-model to:
ng-model="ciudad"
and your ng-disabled to:
ng-disabled="!ciudad"
that shall work
You can validate it like this.
<div ng-controller="MyCtrl">
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<input name="name" ng-model="name" type="text" required >
<br>
<button type="submit" ng-disabled="userForm.$invalid" >Enviar</button>
</form>
</div>
https://jsfiddle.net/ivanm07/y2t88817/

JavaScript username and password verification

I am trying to take a username and password as input and if the entered username and password are admin admin I want to forward them to a new php file. I dont understand where I am going wrong. Any help. Thank you in advance
<html>
<head>
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getelementbyId(log).value;
var pass=document.getelementbyId(password).value;
window.alert("stored");
if((user=="admin")&&(pass="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
</head>
<body>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</html>
Javascript is case sensitive, getelementbyId should be getElementById and id's needs to be wrapped in quotes.
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getElementById('log').value;
var pass=document.getElementById('password').value;
window.alert("stored");
if((user=="admin")&&(pass=="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
Also Note, You have submit button in your form .. which is not handled in validate function, either you can make <input type="button" ... or handle event in validate method.
getelementbyId should be getElementById & enclose the ID name by quote
var user=document.getElementById("log").value;
var pass=document.getElementById("password").value;
And compare by == instead of =
if((user=="admin")&&(pass=="admin"))
^^^
change onclick="validate()" to onclick="return validate();".
this way, when validate returns false, the form won't click. you'd also have to change the validate func to return false when the form doesn't validate, the resulting code would be:
<html>
<head>
<title>
User Validation : 2nd Program
</title>
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
</head>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</text>
</body>
try this one
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
Update: continue and break illustrated.
while(true) {
// :loopStart
var randomNumber = Math.random();
if (randomNumber < .5) {
continue; //skips the rest of the code and goes back to :loopStart
}
if (randomNumber >= .6) {
break; //exits the while loop (resumes execution at :loopEnd)
}
alert('value is between .5 and .6');
}
// :loopEnd

Validating form after error has been shown

I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}

Why does onsubmit function seem not to execute?

I cannot figure out what I'm doing wrong. validateForm() does not seem to execute from an onsubmit. Here is validateForm()
function validateForm() {
var amt = IsNumeric(document.forms["InvGenPay"]["Amount"].value);
alert(amt);
if (amt == false)
{
alert("placeholder to avoid scrolling.");
return false;
}
else
{
return true;
}
}
function IsNumeric(strString)
{
// check for valid numeric strings
var strValidChars = "0123456789.";
var strChar;
var blnResult = true;
if (strString.length == 0) return false;
// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}
}
if (0 > parseFloat(strString))
{
return false;
}
else
{
return blnResult;
}
}
Here is the form with onsubmit:
<script type="text/javascript" language="JavaScript1.2">
document.write('<form name="InvGenPayDonation" action="'+PostURL+'" onsubmit="return validateForm();" method="POST">');
</script>
<input type='text' name='DonationAmount' value="0.00">
In honor of <span style="color: #FF0000"><br />
<input type='text' name='TransDesc' id='TransDesc' value="" >
<input type="submit" value="Next">
</form>
Your biggest issue is that you don't have the right form name (or the right field name for that matter) in your validation code.
var amt = IsNumeric(document.forms["InvGenPay"]["Amount"].value);
vs
'<form name="InvGenPayDonation" action="'+PostURL+'"
Full, working code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Sampe file</title>
<script>
function validateForm() {
// Badly named variable, since this is actually a boolean of 'IsNumeric'
var amt = IsNumeric(document.forms["InvGenPayDonation"]["DonationAmount"].value);
// Can be simplified as simply:
//return amt;
alert('Amt = ' + amt);
if (!amt)
{
alert("placeholder to avoid scrolling.");
return false;
}
else
{
return true;
}
}
function IsNumeric(n) {
// Shamelessly stolen from:
// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
return !isNaN(parseFloat(n)) && isFinite(n);
}
</script>
<body>
<form name="InvGenPayDonation" action="#"
onsubmit="return validateForm();"
method=POST>
<input type='text' name='DonationAmount' value="0.00">
In honor of <span style="color: #FF0000"><br />
<input type='text' name='TransDesc' id='TransDesc' value="" >
<input type="submit" value="Next">
<script>
// Assigned for testing purposes
var PostURL = "#"
document.forms.InvGenPayDonation.action = PostURL;
</script>
</form>
</body>
</html>
You cannot have un-escaped newlines in a JavaScript string. Check your JavaScript console, you are probably getting a syntax error. That error is why the onsubmit is not running.
Also, as suggested, do not use document.write, just write the form normally in HTML, and use JavaScript to add just the POST url.
<form name="InvGenPayDonation" onsubmit="return validateForm();" method="POST">
<input type='text' name='DonationAmount' value="0.00">
In honor of <span style="color: #FF0000"><br />
<input type='text' name='TransDesc' id='TransDesc' value="" >
<input type="submit" value="Next">
</form>
<script type="text/javascript">
document.forms.InvGenPayDonation.action = PostURL;
</script>
P.S. As Jeremy J Starcher pointed out, your form name is wrong inside validateForm.

Validation through getElementById()

I'm been trying to validate my fields by using 'getElementById()' with '.value'. However, it seems like either getElementById.value is not working or some codes has overlap the function.
Updated Javascript function:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("Don leave blank!")
return false;
}
if (isNaN(Tel)) //check only numbers. Same code for FaxNo.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("invalid");
return false
}
return true; //doesn't go to next.php
}
My Form:
<Form action ="next.php" method="post">
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
<input type="submit" name="submit" onclick="return validate();"/>
</Form>
I have already defined my onclick function to my Javascript and tried to add return false too. But the alert still cant appear. Kindly advise.
Your markup is invalid:
<input name="Name" type="text" id="Name" " value=""/>
^-----------should be removed
so correction would be removing all extra " characters:
<input name="Name" type="text" id="Name" value=""/>
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
For preventing submition,when input is invalid, you can try something like a:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
alert("Correct")
else {
alert("Don leave blank!")
return false;
}
if (isNumeric(Tel)) //check only numbers. Same code for FaxNo.
alert("Correct")
else {
alert("invalid");
return false;
}
}
//Borrowed from jQuery lib
function isNumeric( obj ){
return !isNaN( parseFloat(obj) ) && isFinite( obj )
}
<input type="submit" name="submit" onclick="return validate()"/>
Try this,
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") {}
else {alert("Don leave blank!"); return false;}
if (isNaN(Tel)){ alert("invalid"); return false;}
else { }
return true;
}
Your HTML submit button code should be
<input type="submit" name="submit" onclick="return validate()"/>
Use return false to prevent submitting form in case of any validation errors.

Categories

Resources