Javascript Validation Inconsistent - javascript

In the codes below, both functions and callings are quite similar.
Why is it that the JavaScript validation alert works in the code below:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
return( true );
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
but doesn't work in this one:
<!DOCTYPE html>
<html>
<head>
<title> Untitled</title>
<script type='text/javascript'>
}
function validate()
{
if( document.myForm.firstname.value == "" )
{
alert( "Please provide your first name!" );
document.myForm.firstname.focus() ;
return false;
}
return( true );
}
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<input type="submit" value="Submit"/> <br>
</form>
</body>
</html>

Probably because you've got a leading '}' in the code in the second example.
<script type='text/javascript'>
} // <- this is going to cause a syntax error
function validate()
{
if( document.myForm.firstname.value == "" )
{
alert( "Please provide your first name!" );
document.myForm.firstname.focus() ;
return false;
}
return( true );
}
</script>
Try fixing that and see if it works. If you're running things in a browser, check the JavaScript console for errors.

Related

Validate function is not triggered and form is submitted

File with the code bellow is "newrecord.html" presents the form for submitting some record entries that suppose to do the a db and after the users submits the form the validation function is called to check with it's functions the user input.
The form is loaded as normal but after the form is submitted the validation function is not being called and just redirects to to the "newRecord.php"
<!DOCTYPE html>
<html>
<head>
<title>insert New Record</title>
<style>
.recordform {
border:1px solid #999999;
font: normal 14px helvetica;
color: #444444
}
</style>
<script>
function validateAuthor(field)
{
return(field=="") ? "No Author Entered".\n" : ""
}
function validateTitle(field)
{
return(field=="") ? "No Title Entered".\n" : ""
}
function validateCategory(field)
{
return(field=="") ? "No Category Entered".\n" : ""
}
function validateYear(field)
{
if (field=="") return "No Year Entered.\n"
else if (field.length>4)
return "Enter Valid Year value (YYYY).\n"
else if (/[^0-9]/.test(field))
return "Enter only numbers 0-9"
return ""
}
function validateIsbn(field)
{
if (field=="") return "No Isbn Entered.\n"
else if (/[^0-9]/.test(field))
return "Enter only numbers"
return ""
}
function validate(form)
{
fail=validateAuthor(form.author.value)
fail+=validateTitle(form.title.value)
fail+=validateCategory(form.category.value)
fail+=validateYear(form.year.value)
fail+=validateIsbn(form.isbn.value)
if (fail==""){
return true;
}else{
alert(fail);
return false}
}
</script>
</head>
<body>
<table border="0" cellpading="2" cellspacing="5" bgcolor="#eeeeee">
<th colspan="2" align="center">Insert New Record</th>
<form method="post" action="newRecord.php" onsubmit="return validate(this)">
<tr><td>Author</td>
<td><input type="text" maxlength="25" name="author"</td></tr>
<tr><td>Title</td>
<td><input type="text" maxlength="25" name="title"</td></tr>
<tr><td>Category</td>
<td><input type="text" maxlength="25" name="category"</td></tr>
<tr><td>Year</td>
<td><input type="text" maxlength="25" name="year"</td></tr>
<tr><td>Isbn</td>
<td><input type="text" maxlength="25" name="isbn"</td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Insert New Record"></td></tr>
</form>
</table>
</body>
</html>

price range validation using javascript or jquery

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<form method="post" action="form.php">
Price : From
<input type="text" id="price-from">
To:
<input type="text" id="price-to">
<input type="submit">
</form>
</body>
</html>
I want to validate price range ..Price From must be less than Price To.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<form method="post" action="form.php" onsubmit="return validate()">
Price : From
<input type="text" id="price-from">
To:
<input type="text" id="price-to">
<input type="submit">
</form>
</body>
<script>
var validate=function(){
var from=document.getElementById("price-from").value;
var to=document.getElementById("price-to").value;
if(from<to)
return true;
alert("from>=to");
return false;
}
</script>
</html>
call this method on submit
function validatePrices()
{
var priceFrom = parseFloat( $( "#price-from" ).val() );
var priceTo = parseFloat( $( "#price-to" ).val() );
if ( !isNaN( priceFrom ) && !isNaN( priceTo) )
{
if ( priceFrom >= priceTo )//if greater than or equal to then show error alert
{
alert( "price from should be less than price to" );
return false;
}
}
else
{
alert( "price from and price to should be valid numbers " );
return false;
}
}
You may want to give an id to your submit button.
$(functoin() {
var fromPrice = $("#price-from").val();
var toPrice = $("#price-to").val();
if (fromPrice != "" && toPrice != "") {
if (parseFloat(toPrice) > parseFloat(fromPrice) {
$("#frmPrice").submit()
}
});
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<form method="post" action="form.php" id='frmPrice'>
Price : From
<input type="text" id="price-from">To:
<input type="text" id="price-to">
<input type="submit" id="btnSubmit">
</form>
</body>
</html>

Add enter for submit textarea

Hi i was created a new chat box,everithing is working but i need to when i click enter to sumit a message(to go to function Kucaj() ).Can you help me with that?
I add some code for enter but didnt work.Thanks
<?php
session_start();
if(!isset($_SESSION['username'])){
?>
<form name="forma2" action="login.php" method="post">
<table>
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" />
<tr>
<td colspan="2"><input type="submit" name"submit" value"Login"/td>
</tr>
<tr>
<td colspan="2">Registruj se!</td>
</tr>
<?php
exit;
}
?>
<html>
<head>
<title>Maturski rad</title>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script>
function Klikni(){
if(forma1.msg.value == ''){
alert('Upisi poruku!');
return;
}
var msg = forma1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
forma1.msg.value='';
}
xmlhttp.open('GET','insert.php?&msg='+msg,true);
xmlhttp.send();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlogs').load('logs.php');}, 2000);
});
</script>
</head>
<body>
<form name="forma1" action="#" id="forma1">
Username: <b><?php echo $_SESSION['username']; ?></b></br>
Poruka: <br />
<textarea name="msg" style="width:500px; height:100px"></textarea><br />
Posalji<br /><br />
Izloguj se<br /><br />
<script>
$("forma1").keypress(function(event) {
if (event.which == 13) {
event.Klikni();
}}
</script>
<div id="chatlogs">
Molim sacekajte da se ocita!!!
</div>
</body>
</html>
You can just add onsubmit=return Klikni(); attribute to your form and return false; to Klikni function without using .keypress(). Form submitted on user pressing enter is a default behaviour.
function Klikni(e) {
alert("Enter pressed");
return false;
}
<form name="forma1" action="#" id="forma1" onsubmit="return Klikni();">
Put your cursor into the field and press Enter.<br>
<input type="text">
</form>
try like this source,
form.submit(function(e) {
e.preventDefault();
$(this).find('[type=submit]').click();
$("form").submit();
})
Try keydown instead of keypress as:
$("forma1").keydown(function(event) {
You may use like this.It should be like this Klikni(); not like event.Klikni();
<script>
$("forma1").keypress(function(event) {
if (event.which == 13) {
Klikni(); //no need of event there..
}}
</script>

How do I make ajax interact with a database in order to post, get, and delete?

How do I use ajax to post/delete/get to and from a database?
I want to be able to post and be able to delete whatever I post to this link:
http://www.bmoseley.com/ajax/listrecords.php
(this is an assignment)
however, I have to use /ajax/addrecord.php and /ajax/deleterecord.php in order to be able to add and delete posts to /ajax/lisrecords.php
Let me state this: I don't want you to assume that you're doing an assignment for me, I want someone to explain how wrong I am with my code and understanding of ajax and what ajax script I can use in order to accomplish my goal.
This is my code:
HTML:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" type="text/css">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
function validateForm ()
{
var x=document.forms["myForm"] ["fullname"].value;
if (x==null || x=="")
{
alert ("First name must be filled out");
return false;
}
}
function isNumberKey(evt) {
var e = evt || window.event; //window.event is safer,
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 47 || charCode > 57))
return false;
if (e.shiftKey) return false;
return true;
}
</script>
</head>
<body>
<div id="wrap">
<div id="wrapper">
<div id="info">
<form name="myForm" onsubmit="return validateForm()" method="get" action="http://www.bmoseley.com/ajax/listrecords.php">
<table border="0">
<tr>
<td><input class="fullname" maxlength="50" type="text" name="fname" placeholder="Name</td>
</tr>
<tr>
<td><input class="phonenumber" maxlength="10" onkeypress="return isNumberKey(event)" placeholder="Phone Number"></td>
</tr>
<tr>
<td><input class="button" type="submit" value="Submit"></td>
</tr>
</table>
</form>
</div>
<div id="displayInfo">
<script>
$.ajax({
type: 'GET',
data: JSON.stringify(foo),
url: "http://www.bmoseley.com/ajax/listrecords.php",
success: function(data){console.log(data);},
failure: function(e){console.log('ERROR: ' + e)}
});
</script>
</div>
</div>
</div>
</body>
</html>
your form is directly sending to your php-file, you must prevent it to submit to your php, but to send via your ajax request:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" type="text/css">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
function validateForm () {
var x=document.forms["myForm"] ["fullname"].value;
if (x==null || x=="")
{
alert ("First name must be filled out");
return false;
}
}
function isNumberKey(evt) {
var e = evt || window.event; //window.event is safer,
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 47 || charCode > 57))
return false;
if (e.shiftKey) return false;
return true;
}
</script>
</head>
<body>
<div id="wrap">
<div id="wrapper">
<div id="info">
<form id="myForm" method="get" action="/ajax/listrecords.php">
<table border="0">
<tr>
<td><input class="fullname" maxlength="50" type="text" name="fname" placeholder="Name</td>
</tr>
<tr>
<td><input class="phonenumber" maxlength="10" onkeypress="return isNumberKey(event)" placeholder="Phone Number"></td>
</tr>
<tr>
<td><input class="button" type="submit" value="Submit"></td>
</tr>
</table>
</form>
<div id="displayInfo">
</div>
<script>
//loaded when dom is ready
$(function() {
var frm = $('#myForm');
//submit is nearly the same as onsubmit in your html before
frm.submit(function (ev) {
//preventDefault prevents the form to submit normally, because you dont want this, you want ajax!
ev.preventDefault();
//validating your form
if(validateForm())
{
//if valide make the request
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
//or when data is only a string you could add it to your div
$('#displayInfo').html(data);
}
});
}
});
});
</script>
</div>
</div>
</div>
</body>
</html>
in the ajax-jquery-docs you will find more examples.

Validating multiple fields in a form

I was doing the testing for the first time. I read the this code and made one of my own from it. The thing is that its not giving any error even if the fields are left empty.
Here is my fiddle.
Please help out. Thanks.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
{function validateForm()
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
{
if (y==null || y=="")
alert("Password name must be filled out");
return false;
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name*: <input type="text" name="name"> <br>
Password*: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
​
Fixed code: jsfiddle
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validateForm() {
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
if (y==null || y=="") {
alert("Password name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name*: <input type="text" name="name"> <br>
Password*: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
<html>
Be careful of where you place your braces. Additionally, it is advantageous to use the console on your browser to identify some errors and fixed them.
​
Your brace should be after function validateForm() and after the if, and at the end of the function. Overall, the braces are screwed in this example.
Lay your code out so the opening and closing braces match up and make sense to you.
You missed some braces {} and one was in the wrong spot.
Hope this works:
function validateForm() {
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
{
if (y==null || y=="")
alert("Password name must be filled out");
return false;
}
}
You misplaced the braces { } for validation of password. Place them after if clause.
I found it on Internet after a long time searching.. But it works just perfect..
The html code
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
the javascript
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
and the function for email validation
<script type="text/javascript">
<!--
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
you can check it online here

Categories