Can anyone please tell me what the problem is with this code:
function c(id)
{
var empty = document.getElementById(id);
if(empty.length<1)
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
}
This is my html code:
<textarea rows="3" cols="80" id="ta1" onChange="c('ta1');"></textarea>
The value property of the textarea should be checked to determine if it is empty.
var content = document.getElementById(id).value;
if(content.length<1)
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
Working Example: http://jsfiddle.net/35DFR/2/
Try this:
function c(id)
{
if(document.getElementById(id).value == '')
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
}
If you want to go a bit further, you might want to trim the value first though.
Update:
From the comments, try changing the 'onchange' to 'onkeyup':
<textarea rows="3" cols="80" id="ta1" onkeyup="c('ta1');"></textarea>
if (YOURFORM.YOURTEXTFIELDVARIABLENAME.value == "")
{
return True
}
function c(id) {
var empty =document.getElementById(id);
if(!empty.value){
window.alert("This field cant be left empty");
return true;
}else{
return false;
}
}
try this
Related
*I want to display two input fields for lower and higher number and display the necessary error messages if the inputs are wrong.
Any idea why nothing happens when I click on my button? Any way I can shorten my if-else statement cus it does feel quite wordy thank you would appreciate the comments*
<html> Enter lowest number<br>
<input type="text" id="input" size="20">
<span id="wrongInput"><br><br>
Enter highest number<br>
<input type="text" id="input2" size="20">
<span id="wrongInput2"></span><br><br>
<button type="button" onclick="testNum()">Play button</button><br><br>
</html>
<script>
function testNum()
{
//if is not a number or blank input
if (/^\d$/.test(input) == '')
{
var blank = document.getElementById("wrongInput").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input) == false)
{
var wrong = document.getElementById("wrongInput").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (/^\d$/.test(input2) == '')
{
var blank = document.getElementById("wrongInput2").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input2) == false)
{
var wrong = document.getElementById("wrongInput2").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (input2 < input)
{
var wrong = document.getElementById("wronginput2").innerHTML;
wrong.innerHTML = "The number must be higher";
wrong.style.color ="red";
return false;
} else {
return true;
}
}
</script>
The function is called in your example, there are just a few things listed below, that I think you should consider.
First of all you are trying to call an undefined variable in all of the else-blocks.
Second, you are calling innerHTML twice in all of the if statements.
Finally you need to take a look on your conditions in the if statements.
I have 2 text boxes with default value 0 and a submit button.Before submitting I am calling the following javascript function onSubmit="return(validate_myfrm());".I am not able to validate text_1 with value 0.But for text_2 the default value 0 is validated.
function validate_myfrm()
{
var ans;
if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 1?");
if(ans== true)
{
document.myfrm.txt_1.value=0;
document.myfrm.txt_2.focus();
}
else
{
document.myfrm.txt_1.focus();
}
return false;
}
if(document.myfrm.txt_2.value=="" ||document.myfrm.txt_2.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 2?");
if(ans== true)
{
document.myfrm.txt_2.value="0";
return true;
}
else
{
document.myfrm.txt_2.focus();
}
return false;
}
return true;
}
If i return true; after document.myfrm.txt_2.focus(); the page is redirected to next page without confirming the values for txt_2.Pls help
your first condition should be like this
if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0)
{
}
Use Else If Instaed of if function now it will validate before submission.
function validate_myfrm()
{
var ans;
if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 1?");
if(ans== true)
{
document.myfrm.txt_1.value=0;
document.myfrm.txt_2.focus();
}
else
{
document.myfrm.txt_1.focus();
return false;
}
}else if(document.myfrm.txt_2.value=="" ||document.myfrm.txt_2.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 2?");
if(ans== true)
{
document.myfrm.txt_2.value="0";
return true;
}
else
{
document.myfrm.txt_2.focus();
}
return false;
}
return true;
}
}
document.myfrm.txt_bb1.value==0
should be: document.myfrm.txt_1.value==0
also:
Upon setting a return, the function will end and return the false or true set out in your function.
the first if when values are "" or 0 according your condition will always return false. since it is returning false, the function will end and return false.
edit:
here a simple validation example:
<form id="myfrm" name="myfrm" onSubmit="return(validate_myfrm());">
<input type="text" name="txt_1" value="" />
<input type="text" name="txt_2" value="" />
<input type="submit" value="submit" />
</form>
<span id="result"></span>
<script>
function validate_myfrm()
{
if(document.myfrm.txt_1.value!="" && document.myfrm.txt_2.value!="")
{
return true;
} else {
document.getElementById("result").innerHTML="Error fields cannot be empty";
return false;
}
}
</script>
remember in this, that whenever you use return in a function, it will stop the function and return the value set.
What's wrong in it why it's not working...
<script language="JavaScript" type="text/javascript">
//function to check empty fields
function isEmpty(strfield1, strfield2) {
//change "field1, field2 and field3" to your field names
strfield1 = document.forms[0].name.value
strfield2 = document.forms[0].email.value
//name field
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ') {
alert( "Name is a mandatory field.\nPlease amend and retry.")
return false;
}
//EMAIL field
if (strfield2 == "" || strfield2 == null || !isNaN(strfield2) || strfield2.charAt(0) == ' ') {
alert(" Email is a mandatory field.\nPlease amend and retry.")
return false;
}
return true;
}
//function to check valid email address
function isValidEmail(strEmail){
validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
strEmail = document.forms[0].email.value;
// search email text for regular exp matches
if (strEmail.search(validRegExp) == -1) {
alert('A valid e-mail address is required.\nPlease amend and retry');
return false;
}
return true;
}
//function that performs all functions, defined in the onsubmit event handler
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
return false;
}
</script>
It doesn't do anything I don't understand what's going there and in form I put this too
<form onsubmit="return check(this);" action="sendquery.php" name="contquery">
First glance: too many brackets as shown by #FishBasketGordo so I will not repeat
Second glance - you pass the field and do not test the field value
Third glance: You do not pass the correct names to the function
Fourth glance - isEmpty returns false when empty. It should return true
I fixed all those
DEMO HERE
Complete page to show where what goes. Updated to do unobtrusive event handling on the form
<html>
<head>
<title>Validation</title>
<script type="text/javascript">
// trim for IE
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
//function to check empty fields
function isEmpty(objfld) {
var val = objfld.value;
if (val.trim() == "" || val == null) {
alert(objfld.name+" is a mandatory field.\nPlease amend and retry.");
objfld.focus();
return true;
}
return false;
}
//function to check valid email address
function isValidEmail(objEmail){
var validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
var strEmail = objEmail.value;
if (strEmail.match(validRegExp)) return true;
alert('A valid e-mail address is required.\nPlease amend and retry');
objEmail.focus();
return false;
}
//function that performs all functions, defined in the onsubmit event handler
function validate(form) {
if (isEmpty(form.name)) return false;
if (isEmpty(form.email)) return false;
return isValidEmail(form.email);
}
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
return validate(this);
}
}
</head>
<body>
<form id="form1">
Name:<input type="text" name="name" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" />
</form>
</body>
</html>
Probably the main reason it isn't working is the syntax errors:
// Syntax error ----v
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
// The return statement should be above the previous closing bracket
// and the final closing bracket removed.
return false;
}
There's an extra closing paren on the first line, and there are too many closing brackets. If you open up this up in FireBug or Chrome Developer Tools or a similar tool, it would tell you about this automatically.
The following code is not working. Want to check white spaces in an input field. If there are not any white spaces want to alert. Any help
<script language="javascript">
document.register.eventdtls.value;
function hasWhiteSpace(strg) {
var whiteSpaceExp=/\s+$/;
if (whiteSpaceExp.test(strg))
alert("Please Check Your Fields For Spaces");
return false;
else
return true;
}
</script>
You are missing brackets:
if (whiteSpaceExp.test(strg)) {
alert("Please Check Your Fields For Spaces");
return false;
} else {
return true;
}
Your current regex will only test for spaces at the end of the string (that's what the $ represents here);
Your regex should be:
var whiteSpaceExp=/\s+/;
Also, you need to put brackets around your if(){ } else{ } because you have multiple statements.
function hasWhiteSpace(strg) {
var whiteSpaceExp = /\s+/;
if (whiteSpaceExp.test(strg)) {
alert("Please Check Your Fields For Spaces");
return false;
}
else {
return true;
}
}
Kindly Use braces in your 'if' statement
if (whiteSpaceExp.test(strg))
{
alert("Please Check Your Fields For Spaces");
return false;
}
else
return true;
I have a JavaScript function for a form. The code is :
<script type="text/javascript">
function verify() {
if (isNaN(document.form1.exp_amount.value) == true) {
alert("Invalid Block Amount");
return false;
} else if ((document.form1.exp_name.value).length == 0) {
alert("Block Exp is left Blank!");
return false;
} else if ((document.form1.exp_amount.value).length == 0) {
alert("Block Amount is left Blank!");
return false;
} else {
document.form1.submit();
return true;
}
}
</script>
Now I have to provide Alphabet Validation for it, which I have it in a separate JS function:
<script language="javascript" >
function checkName() {
re = /^[A-Za-z]+$/;
if (re.test(document.exp_name.form1.value)) {
alert('Valid Name.');
} else {
alert('Invalid Name.');
}
}
</script>
If I want to have Alphabet validation inside function verify(), how could I do it? Are there any other ways?
Please change your validation and form to this which will allow submission of the form if valid and not if errors. The following code is in my opinion canonical and will work on all browsers that support regular expressions (which was introduced in JS1.1 in 1996 with NS3.0) - please note that javascript does not support dashes in names unless you quote the field name in the script. The code does not need the form to be named since it passes the form object in the call (this) and uses the object in the function as theForm
<html>
<head>
<title>Canonical forms validation without jQuery</title>
<script type="text/javascript">
var validName = /^[A-Za-z]+$/;
function checkName(str) {
return validName.test(str);
}
function verify(theForm) {
// note: theForm["..."] is short for theForm.elements["..."];
var amount = theForm["exp_amount"].value;
if(amount ==""){
alert("Block Amount is left blank");
theForm["exp_amount"].focus();
return false;
}
if (isNaN(amount)) {
alert("Invalid Block Amount");
theForm["exp_amount"].focus();
return false;
}
var name = theForm["exp_name"].value;
if(name.length==0) {
alert("Block Exp is left Blank!");
theForm["exp_name"].focus();
return false;
}
if(!checkName(name)) {
alert("Block Exp is invalid!");
theForm["exp_name"].focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return verify(this)">
Amount: <input type="text" name="exp_amount" value="" /><br />
Name: <input type="text" name="exp_name" value="" /><br />
<input type="submit" />
</form>
</body>
</html>
Simply return false or true inside your checkName function:
function checkName()
{
re = /^[A-Za-z]+$/;
if(re.test(document.exp_name.form1.value))
{
alert('Valid Name.');
return true;
}
else
{
alert('Invalid Name.');
false;
}
}
Then call it and check the result.
...
else if((document.form1.exp_amount.value).length==0)
{
alert("Block Amount is left Blank!");
return false;
}
else if (!checkName()) {
return false;
}
else
{
document.form1.submit();
return true;
}
As an aside, there are many ways your code can be cleaned up and improved. I don't want to get into them now, but if you'd like to discuss it, just leave a comment.
Edit your checkName() function to
function checkName()
{
re = /^[A-Za-z]+$/;
if(re.test(document.exp_name.form1.value))
{
alert('Valid Name.');
return true;
}
else
{
alert('Invalid Name.');
return false;
}
}
And add
else if(!checkName()){ return false;}
to your validation code just before the form submit
<script type="text/javascript">
function verify()
{
if(isNaN(document.form1.exp_amount.value)==true)
{
alert("Invalid Block Amount");
return false;
}
else if((document.form1.exp_name.value).length==0)
{
alert("Block Exp is left Blank!");
return false;
}
else if((document.form1.exp_amount.value).length==0)
{
alert("Block Amount is left Blank!");
return false;
}
else if(!(/^[A-Za-z]+$/.test(document.form1.exp_amount.value))) //ADD THIS
{
alert('Invalid Name');
return false;
}
document.form1.submit();
return true;
}
</script>