JavaScript and client side scripting.
Moderator: General Moderators
social_experiment
DevNet Master
Posts: 2793 Joined: Sun Feb 15, 2009 11:08 am
Location: .za
Post
by social_experiment » Tue Mar 13, 2012 3:28 am
I have a javascript function that checks whether a field is empty or not; the html code
Code: Select all
<label id="name">Name (*)</label>
<input id="fieldName" maxlength="30" name="name" size="30" onblur="return emptyFieldCheck('name');" type="name" />
The javascript in question
Code: Select all
function emptyFieldCheck(field)
{
var myForm = document.forms[1];
var fieldName = myForm.field;
var textField = fieldName.value;
if (textField == '') {
alert('Error message');
return false;
}
return true;
}
The error message is receive from the error console is
fieldName is undefined ; Any ideas? The code works if i replace 'field' with 'name' but i would like the function to be reuseable.
Thanks in advance
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
theserve
Forum Newbie
Posts: 24 Joined: Wed Jan 18, 2012 6:35 am
Location: London
Post
by theserve » Tue Mar 13, 2012 4:22 am
in your function it looks like you are trying to check the value of the form directly rather than using the value passed through.
Try changing this line:
var fieldName = myForm.field;
to
var fieldName = field;
social_experiment
DevNet Master
Posts: 2793 Joined: Sun Feb 15, 2009 11:08 am
Location: .za
Post
by social_experiment » Tue Mar 13, 2012 4:47 am
Thanks for the feedback; It didn't work but i went a different route when you mentioned that i was trying to access the form as opposed to the value;
Code: Select all
var fieldName = document.getElementById(field);
var textField = fieldName.value;
The removes the need for
var myForm = document.forms[1]; aswell;
What i don't understand is that using the value from the input field "name" attribute outright like this works
Code: Select all
var emailField = myForm.email.value;
but in my function it doesn't work; does javascript assume i am looking for a field with name attribute value of 'field' in this situation?
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
requinix
Spammer :|
Posts: 6617 Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA
Post
by requinix » Tue Mar 13, 2012 6:13 am
social_experiment wrote: does javascript assume i am looking for a field with name attribute value of 'field' in this situation?
Yes.
theserve has the right idea but it needs a little more:
Code: Select all
function emptyFieldCheck(field)
{
var textField = field.value;