Jump to content
mboehler3

Validation Code For Form Element By Id

Recommended Posts

Hi, I'm using id tags for some fields on my form. My "First Name" field looks like this:

<input id="firstname" name="LastName" size="24" maxlength="250" tabindex="1" value="First Name*" onfocus="if(this.value == 'First Name*') {this.value = '';}" onblur="if (this.value == '') {this.value = 'First Name*';}" />

As you can see, the field has a value set as "First Name*", indicating the first name field. I want to set the JavaScript validation so that, if a user leaves the field with "First Name*" or leaves the field blank, they are hit with a popup message that tells them to enter in their first name. Here's the JavaScript I have set up:

if (document.getElementById('firstname').innerHTML == 0) {			   message = message + "Please enter your First Name.\n";		   }		   else {			   if (document.getElementById('firstname').value == 'First Name*') {				   message = message + "Please enter your First Name.\n";			   }		   }

This isn't working though, when I enter in my first name I am still asked to enter in my first name. Not sure what the issue is, can someone please offer some advice? Thanks in advance for your help and time.

  • Like 1

Share this post


Link to post
Share on other sites

you check the value not innerhtml, and you have not set the type for input, anyway use defaultValue

if (document.getElementById('firstname').value == "" || document.getElementById('firstname').value == document.getElementById('firstname').defaultValue) {message = message + "Please enter your First Name.\n";}

Share this post


Link to post
Share on other sites

I'm not sure where you are calling that code from, but I would just create a function for handling the blur event of the input

<input id="firstname" name="LastName" size="24" maxlength="250" tabindex="1" value="First Name*" onfocus="if(this.value == 'First Name*') {this.value = "";}" onblur="checkFirstName()" />  function checkFirstName = function(){  var value = document.getElementById('firstname').value;  if(value === "" || value === "First Name*"){	if(value === ""){	   value = "First Name*";	};	//tell them that they need to enter their first name still  };};

I'm also not sure why you are trying to compare it's innerHTML to 0, either...

Edited by thescientist

Share this post


Link to post
Share on other sites

Why are you comparing the innerHTML of a text field with 0? What do you think the innerHTML of that field represents?

Share this post


Link to post
Share on other sites

Oops <input id="firstname" name="LastName" size="24" maxlength="250" tabindex="1" value="First Name*" onfocus="if(this.value == 'First Name*') {this.value = "";}" onblur="checkFirstName()" /> one function to check all

function checkIfEmptyOrDefaultvalue(elem)	{ 	  var this_input = document.getElementById(elem.id);  	  if(this_input.value == "" || this_input.value == this_input.defaultValue)		  {this_input.value=this_input.defaultValue;		message = message + "Please enter your "+this_input.defaultValue+".\n";		 }	} <input type="text" id="firstname" name="FirstName" size="24" maxlength="250" tabindex="1" value="First Name*" onfocus="if(this.value == 'First Name*') {this.value = '';}" onblur="checkIfEmptyOrDefaultvalue(this);" /><input type="text" id="lastname" name="LastName" size="24" maxlength="250" tabindex="2" value="Last Name*" onfocus="if(this.value == 'Last Name*') {this.value = '';}" onblur="checkIfEmptyOrDefaultvalue(this);" /> 

Edited by dsonesuk

Share this post


Link to post
Share on other sites
you check the value not innerhtml, and you have not set the type for input, anyway use defaultValue
if (document.getElementById('firstname').value == "" || document.getElementById('firstname').value == document.getElementById('firstname').defaultValue){message = message + "Please enter your First Name.\n"; }

I couldn't get this to work... copied and pasted exactly what you wrote. I don't get any pop up that tells me to enter First Name.

Share this post


Link to post
Share on other sites
Why are you comparing the innerHTML of a text field with 0? What do you think the innerHTML of that field represents?
Not sure, I simply searched for how to create javascript validation for a field based on the id and not the name, and that's what I found. Now I understand this is incorrect.

Share this post


Link to post
Share on other sites
I'm not sure where you are calling that code from, but I would just create a function for handling the blur event of the input
<input id="firstname" name="LastName" size="24" maxlength="250" tabindex="1" value="First Name*" onfocus="if(this.value == 'First Name*') {this.value = "";}" onblur="checkFirstName()" />  function checkFirstName = function(){  var value = document.getElementById('firstname').value;  if(value === "" || value === "First Name*"){	if(value === ""){	   value = "First Name*";	};	//tell them that they need to enter their first name still  };};

I'm also not sure why you are trying to compare it's innerHTML to 0, either...

I had trouble getting this to work too. I copied everything you wrote and pasted the input into my form, and the javascript in my validation code. The form accepts blank fields with this code.

Share this post


Link to post
Share on other sites

when you say pop-up do you mean alert, have you set up a alert somewhere to show the message? its not shown anywhere in original code. if not try this

 var message="";function checkIfEmptyOrDefaultvalue(elem)	{ 	  var this_input = document.getElementById(elem.id);	message="";	  if(this_input.value == "" || this_input.value == this_input.defaultValue)		  {		this_input.value=this_input.defaultValue;		message = message + "Please enter your "+this_input.defaultValue+".\n";		alert(message)		 }	}

with

 <input type="text" id="firstname" name="FirstName" size="24" maxlength="250" tabindex="1" value="First Name*" onfocus="if(this.value == 'First Name*') {this.value = '';}" onblur="checkIfEmptyOrDefaultvalue(this);" /><input type="text" id="lastname" name="LastName" size="24" maxlength="250" tabindex="2" value="Last Name*" onfocus="if(this.value == 'Last Name*') {this.value = '';}" onblur="checkIfEmptyOrDefaultvalue(this);" /> 

Edited by dsonesuk

Share this post


Link to post
Share on other sites
I had trouble getting this to work too. I copied everything you wrote and pasted the input into my form, and the javascript in my validation code. The form accepts blank fields with this code.
well, did you add your own logic? Maybe you should post what you have tried and tell us if you are getting any errors in the process. It's also unclear if you are trying to get a pop-up to display, or just show a message on the page. I think most of these suggestions will work if they are correctly implemented and have a little basic testing done on them by yourself.

Share this post


Link to post
Share on other sites

Ok, I'm getting a little confused so I will post all of my code. I want a popup to happen just like the form on this page: http://www.surepayroll.com/product/payroll/. Hit the submit button and you'll see the "pop-up" I'm referring to. Here is my form code:

<script language="JavaScript" src="/surechoice/pminewsletter_check.js" type="text/javascript"></script>  <form action="http://now.eloqua.com/e/f2.aspx" method="post" name="referaclient" onSubmit="return checkrefervalues();">  <img src="/images/960/accountant-center/form/partnership-top.gif" /><div class="partnership-form"><div class="fontsize18 lineheight22 bpadding10"><strong>Subscribe to Practice Management Insights</strong></div><div class="acct-field"><input id="firstname" name="LastName" size="24" maxlength="250" tabindex="1" value="First Name*" onfocus="if(this.value == 'First Name*') {this.value = "";}" onblur="checkFirstName()" /></div><div class="acct-field"><input type="text" id="lastname" name="LastName" size="24" maxlength="250" tabindex="2" value="Last Name*" onfocus="if(this.value == 'Last Name*') {this.value = '';}" onblur="checkIfEmptyOrDefaultvalue(this);" /></div><div class="acct-field"><input id="company" name="Company" size="24" maxlength="250" tabindex="1" value="Company*" onfocus="if(this.value == 'Company*') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Company*';}" /></div><div class="acct-field2"><input id="email" name="Email" size="24" maxlength="250" tabindex="1" value="Email*" onfocus="if(this.value == 'Email*') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Email*';}" /></div><div align="right" class="rpadding10">*Required Fields</div><input src="/images/960/accountant-center/form/partnership-submit.jpg" class="rpadding10" name="Submit" value="Submit" type="image" align="right" /></div><img src="/images/960/accountant-center/form/partnership-bottom.gif" class="iebottom bpadding15" /></form>

And here's the pminewsletter_check.js file:

	   function checkrefervalues(){		   message = "";		   function checkFirstName = function(){								  var value = document.getElementById('firstname').value;								  if(value === "" || value === "First Name*"){									    if(value === ""){										   value = "First Name*";									    };									    //tell them that they need to enter their first name still								  };							    };	   	    if (message.length > 0){	  									    alert(message);									    return false;									    }							    pageTracker._trackEvent('Accountant Forms', 'PMISubscription');									  							    return true;							    }         	   function checkemail(str){	    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i	    if (filter.test(str))	    testresults=true	    else{	    message = message + "Email address seems incorrect (check @ and .'s)\n"	    return false;	    }	    }	   function IsNumeric(sText)	    {		   var ValidChars = "0123456789";		   var IsNumber=true;		   var Char;	   				   for (i = 0; i < sText.length && IsNumber == true; i++)			  {			  Char = sText.charAt(i);			  if (ValidChars.indexOf(Char) == -1)				 {				 IsNumber = false;				 }			  }		  return IsNumber;		   }	 		  var isNN = (navigator.appName.indexOf("Netscape")!=-1);					    function autoTab(input,len, e) {						  var keyCode = (isNN) ? e.which : e.keyCode;						  var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];						  if(input.value.length >= len && !containsElement(filter,keyCode)) {						    input.value = input.value.slice(0, len);						    input.form[(getIndex(input)+1) % input.form.length].focus();						  }						  function containsElement(arr, ele) {						    var found = false, index = 0;						    while(!found && index < arr.length)						    if(arr[index] == ele)						    found = true;						    else						    index++;						    return found;						  }						  function getIndex(input) {						    var index = -1, i = 0, found = false;						    while (i < input.form.length && index == -1)						    if (input.form[i] == input)index = i;						    else i++;						    return index;						  }						  return true;					    }

All I want to do is get the popup to happen when a field is blank or has the pre-populated value.

Share this post


Link to post
Share on other sites

wow. Well, it looks like your check function it just a bunch of function itself. Given this whole approach, it makes a little more clearer what you want to do however. So, why not just make your function just get the value of each element/field you want to validate, check it for something, add your messaging, and going until the end. When you get to the end, just alert a message if message is != "" anymore. Just so you know, validating onsubmit is different from setting/resetting the input field onblur/onfocus. From your original posts, it was unclear what you wanted to happen and where and when. I suppose that's why there's so much confusion.

Share this post


Link to post
Share on other sites

Function creation within a function, THATS not going to work. That website code checks all values after submission and returns false to prevent submission, or true to submit. you asked for message after a user leaves a single input field, different ball game altogether I'm afraid.

Edited by dsonesuk

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...