Jump to content

Using Javascript to access form labels


ThePsion5

Recommended Posts

Hi, I'm writing a piece of javascript code that validates a form field by using an alert box. I want this code to by dynamic, so instead of writing the individual messages myself I want to use the label field in the message. FOr example, here's the HTML:

<label for ='email'>E-Mail Address</label><textarea name='email' id='email' />

And here's what I want the alert field to say:

Please enter an appropriate E-Mail Address
Shouldn't I be able to use DOM to do this? I think so, but i'm not sure and i'm not exactly sure how to go about this. Ideally, I could specify what field i'd be looking for as a function paramater. Any assistance?
Link to comment
Share on other sites

You can make a loop in the function that triggers the alert, in which loop you can access the element (eg by ID) that is parent of all the labels. And then fetch the innerHTML. Like this:

var myForm = document.forms["form_of_labels"];var Labels = myForm.getElementsByTagName("label");for (L=0; L<Labels.length; L++){ var dataField = document.getElementById(Labels[L].for) if (dataField.value == "") //all validations for all fields at the same time alert ("Please enter an appropriate "+Labels[L].innerHTML);}
Link to comment
Share on other sites

You can make a loop in the function that triggers the alert, in which loop you can access the element (eg by ID) that is parent of all the labels. And then fetch the innerHTML. Like this:
Cool, that works pretty well. Could I also do the same thing given only the ID of the form element? I think i'd have to do something like this:
function alertAndFocus(formName, fieldName, alertMessage){  var thisForm = document.forms[formName];  var labels = thisForm.getElementByTagName("label");  for(var i=0; i < labels.length; i++)  {	var field = document.getElementByID(fieldName[i].for);	var label = field.value;	alert(alertMessage . label);  }}

Then call the function like so:

alertAndFocus('someForm', 'requiredField', 'Please Enter a value for:')

To create an alertbox that says this:

Please enter a value for: (the label for the field)
Is this correct? Sorry to be a pain, but i'm not as experienced with JavaScript as i'd like to be. Thanks! :)
Link to comment
Share on other sites

Well, the idea of the script I wrote, was to validate all fields after the form was submitted. Making a function of that piece of code, I just don't know where you want to call that function. This piece of script sould be called upon submit, anywhere else could probably cause problems, I suppose. What is your intension of making a function?

Link to comment
Share on other sites

Well, the idea of the script I wrote, was to validate all fields after the form was submitted. Making a function of that piece of code, I just don't know where you want to call that function. This piece of script sould be called upon submit, anywhere else could probably cause problems, I suppose. What is your intension of making a function?
Well the Idea is that i'd have several function so validate, one for each type of validation. For example:
function isBlank( stringValue ){  var isBlank = false;  if( stringValue.replace(/(^\s+)|(\s+$)/g, '').length < 1 )	isBlank = true;  return isBlank;}

So then I would create a script like so:

function validateForm(formName){  alertValue = 'Please Enter a Value For: ';  isValid = false;  if(isBlank(formfield.value))	alertAndFocus(formName, 'formField', alertValue);  else	isValid = true;  return isValid;}

Granted, that's a simplified (and probably syntactically incorrect) version of it, but that's the general idea.

Link to comment
Share on other sites

The syntax seems correct to me, unless its this:if(isBlank(formfield.value)), where does "formfield" come from?Anyway, this is fine. You could put all these functions in one though, in a function called "validateform" or something. Using that, remember to return the value that passes permission to submit, from both sides. Eg:

<form name="..." action="..." onsubmit='return validateform()'>
function validateform(){...return false;...return true;}
Link to comment
Share on other sites

I'm defining the required field name statically...so the actual function would be containing a series of if...else statements that would alert the user if a required field was not filled on or some other chriteria isn't met. If all the requirements are met, the function would then return true and the form would be submitted. This is actually part of this grand scheme I have to dynamically generate form validation javasript using PHP and GET values, lol. the formfield.value is actually going to be defined by the PHP script based on what's passed into it from the GET field. Whether this will actually work in the end...who knows, heh.

Link to comment
Share on other sites

I would have suggested PHP too in the beginning, but I keep saying that in the JavaSctipt forum :) Besides, you are using javascript, and it can be fully converted to php code, javascript validation would not be necessary. :)

Link to comment
Share on other sites

What do you mean? Validating at both client and server-side doesn't compete with a full validate at server-side :) Javascript can be shut down by the user, or even altered anyway. The javascript must be not more than a suggestion to the user, but the php validation must be a forced one. So even if the user bypasses the javascript validation, it still would not be able to bypass it at php side. You are not supposed to use javascript validation though, its optional. Sometimes users may find it just rather ignoring.What I mean is, if you are going to use php validation anyway, you should make a full one that is safe in all surconstances so that the user cannot post unwanted data. The javascript validation would just prevent the data from submitted, but only if the user doesn't mess with the script on the page :)

Link to comment
Share on other sites

Well obviously I can't depend solely on javascript for validation, but the idea is that most validation errors I can handle on the client-side with javascript, saving the users time and me some bandwidth. Regardless of whether the javascript validation is functioning or not I'll still validate everything on the server-side as well, this is used mainly as a convenience to potential users. Personally, I've found that Javascript validation done properly can be helpful and unobtrucive since the users are presented with the error upfront instead of sending their information to the server and waiting to find out what may have gone wrong and possibly having to re-enter information.

Link to comment
Share on other sites

Well obviously I can't depend solely on javascript for validation, but the idea is that most validation errors I can handle on the client-side with javascript, saving the users time and me some bandwidth. Regardless of whether the javascript validation is functioning or not I'll still validate everything on the server-side as well, this is used mainly as a convenience to potential users. Personally, I've found that Javascript validation done properly can be helpful and unobtrucive since the users are presented with the error upfront instead of sending their information to the server and waiting to find out what may have gone wrong and possibly having to re-enter information.
I hate having to retype passwords or captchas when sopmething goes wrong. I prefer javascript validation
Link to comment
Share on other sites

I too hate that, but that is up to the organisation of the server-script. It is very easy to pre save the input data and just refilling it in the error showing form :)If I was confronted with a site that does that, the site would look more professional in my opinion :)(may I show off my own site that does that indeed? :))

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...