/    Sign up×
Community /Pin to ProfileBookmark

Adding function causes code failure

Hello,

I tried to create a function to reduce some in line code. However something is wrong with the function call getGenderChoice() because the code stops working. If I comment out getGenderChoice() and uncomment the lines that would be in the function it works properly. What would possibly be wrong with a function call that seems to follow function rules?

Thanks

[code=php]
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html>
<head>
<title>Main</title>
<script type=”text/javascript”>

function addEventSimple(obj,evt,fn) {
if (obj.addEventListener)
obj.addEventListener(evt,fn,false);
else if (obj.attachEvent)
obj.attachEvent(‘on’+evt,fn);
}

var validationErrorMessage = new Object();
validationErrorMessage[‘required’] = ‘This field is required’;

var validationFunctions = new Object();
validationFunctions[“required”] = isRequired;

function isRequired(formField)
{
switch (formField.type) {
case ‘text’:
case ‘textarea’:
case ‘select-one’:
if (formField.value)
return true;
return false;
case ‘radio’:
var radios = formField.form[formField.name];
for (var i=0;i<radios.length;i++) {
if (radios[i].checked) return true;
}
return false;
case ‘checkbox’:
return formField.checked;
}
}

var W3CDOM = document.createElement && document.getElementsByTagName;

function validateForms() {
if (!W3CDOM) return;
var forms = document.forms;
for (var i=0;i<forms.length;i++) {
forms[i].onsubmit = validate;
}
}

addEventSimple(window,’load’,validateForms);

function validate() {
var els = this.elements;
var validForm = true;
var firstError = null;
for (var i=0;i<els.length;i++) {
if (els[i].removeError)
els[i].removeError();
var req = els[i].getAttribute(‘validation’);
if (!req) continue;
var reqs = req.split(‘ ‘);
for (var j=0;j<reqs.length;j++) {
if (!validationFunctions[reqs[j]])
validationFunctions[reqs[j]] = emptyFunction;
var OK = validationFunctions[reqs[j]](els[i]);
if (OK != true) {
var errorMessage = OK || validationErrorMessage[reqs[j]];
writeError(els[i],errorMessage)
validForm = false;
if (!firstError)
firstError = els[i];
break;
}
}
}

getGenderChoice();

// get gender radio choice
//var formGender=document.forms[0];
//var choices = formGender.elements.gender;
//for(var i=0;i<choices.length;i++)
//{ if(choices[i].checked)
// break;
// else { validForm = false; } }

// form not valid return with error message
if (!validForm) {
alert(“Errors have been found” );
location.hash = ‘#startOfForm’;
return;
}

// alert order is OK
alert(“Your order has been submittedn” + “Name: ” + document.getElementById(‘name’).value +
“nGender: ” + choices[i].value );

return validForm;
}

function getGenderChoice()
{
// get gender radio choice
var formGender=document.forms[0];
var choices = formGender.elements.gender;
for(var i=0;i<choices.length;i++)
{ if(choices[i].checked)
break;
else { validForm = false; }
}
}
</script>
</head>
<body>
<form name=”form1″ id=”startOfForm”>
<table><tbody>
<tr>
<td class=”question”><label for=”name”>Name</label></td>
<td><input name=”name” id=”name” validation=”required” /></td>
</tr>
<tr>
<td class=”question”>Gender</td>
<td>
<input type=”radio” name=”gender” value=”male” rel=”none” id=”gender_male” validation=”required”>
<label for=”gender_male”>Male</label><br />
<input type=”radio” name=”gender” value=”female” rel=”none” id=”gender_female” validation=”required”>
<label for=”gender_female”>Female</label><br />
</td>
</tr>
<tr>
<td colspan=2><input type=”submit” value=”Submit form”></td>
</tr>
</tbody></table>
</form>
</body>
</html>

[/code]

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@ahurttApr 27.2010 — Firstly you didn't declare any variable named 'validForm' local to your getGenerChoice() function. So when within the getGenderChoice() function you say validForm = false, you are not setting the validForm variable you var'ed in the validate() function to false. You're creating some other new global scoped variable named validForm or something and setting it to false but it isn't the same validForm function local var you declared within validate(). Change your getGenderChoice function to be like this:

[CODE]
function getGenderChoice()
{
// get gender radio choice
var formGender=document.forms[0];
var choices = formGender.elements.gender;
for(var i=0;i<choices.length;i++)
{ if(choices[i].checked) {
break;
else { return false; }
}
}
[/CODE]


and change the line in validate() where you call getGenderChoice() to this:

[CODE]
validForm = getGenderChoice();
[/CODE]


On closer look though, I think your logic in the getGenderChoice() function may be faulty. It will return false all the time if the first choice is not checked. Are you just trying to ensure that one or the other of the two radio buttons has been checked? If so try something like this instead:

[CODE]
function getGenderChoice()
{
// get gender radio choice
var formGender=document.forms[0];
var choices = formGender.elements.gender;
for(var i=0;i<choices.length;i++) {
if(choices[i].checked) {
return true;
}
}
return false;
}
[/CODE]


I also notice that if your first for() loop in validate() ends up setting validForm to false, but then the subsequent call to getGenderChoice() were to set it to true, it would look like the form had no errors when in fact it did and you would never see your alert when you should be seeing it. So you may want to add a conditional around the call to getGenderChoice() like so:

[CODE]
if (validForm) {
validForm = getGenderChoice();
}
[/CODE]
Copy linkTweet thisAlerts:
@coolechoauthorApr 27.2010 — Hi, I tried what you suggested but still calling the function genderChoice() wrapped in the if(validForm) does not work. I did overlook the fact that when I put genderChoice in a function it broke the connection with validForm variable. You were correct that if female was checked it did not work. Elsewhere in code (that I removed) it checked that radios are checked. I had to make the code:

[code=php]
var formGender=document.forms[0];
var choices = formGender.elements.gender;
for(var i=0;i<choices.length;i++)
{

if(choices[i].checked)
break;
}
[/code]


Thanks for your help.
Copy linkTweet thisAlerts:
@ahurttApr 27.2010 — You seem to have missed the important bit about making the getGenderChoice() function actually RETURN a value which you then ASSIGN to validForm. Compare my rewritten getGenderChoice() function to what you had to begin with. Please reread my original reply carefully and slowly because there is much more to it than just wrapping the call to getGenderChoice() in an if condition.
×

Success!

Help @coolecho spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...