Jump to content

validate radio buttons help


TOA

Recommended Posts

It's been a while since I programmed in javascript, and am finding myself a little rusty (ok more than a little).

 

I have a form that contains nothing but radio buttons (it's a test/survey)

 

I need to check and see if they left any blank and give them an alert if they did, continue if they didn't.

 

I've found a few scripts online that didn't work, and have butchered them until they were unrecognizable :-[ so I'm doing what I should have done in the first place and turned to you guys.

 

Can anyone help? Maybe just suggest the best way to do it? I definately want it in JS so it validates before submission, but aside from that I'm open and willing to hear any suggestions.

 

Hope you can help me!

Link to comment
Share on other sites

No ideas?

Maybe more info will help. I'm pulling the questions and answers 5 at a time until the end (which usually leaves a number less than 5 on the last page) from a db with php. Each radio button group name is the question number. I just need to check that every question has been answered. I've tried many things but seem to be getting farther from the answer.

 

Here's an example of the source produced:

<form id="myForm" action="process-assessment.php?num=0&num1=5" method="post" onsubmit="return checkForm()"><ul style="display:none;"></ul>
1. How many beers can a person have while eating dinner, and still be able to drive?<br /><ul>
<li style="list-style-type:none;"><input type="radio" name="1" value="1" />1-3</li><br />
<li style="list-style-type:none;"><input type="radio" name="1" value="2" />4-6</li><br />
<li style="list-style-type:none;"><input type="radio" name="1" value="3" />None</li><br />
</ul>
2. Whether or not you drink every day, are there times you drink more than 5 drinks in one sitting?<br /><ul>
<li style="list-style-type:none;"><input type="radio" name="2" value="4" />Yes</li><br />
<li style="list-style-type:none;"><input type="radio" name="2" value="5" />No</li><br />
</ul>
3. In the past six months, have there been days when you have had to cut down or limit your usual activities because of your health?<br /><ul>
<li style="list-style-type:none;"><input type="radio" name="3" value="7" />Yes</li><br />
<li style="list-style-type:none;"><input type="radio" name="3" value="8" />No</li><br />
</ul>
4. Is your blood pressure greater than 120/80 mmHg?<br /><ul>
<li style="list-style-type:none;"><input type="radio" name="4" value="9" />Yes</li><br />
<li style="list-style-type:none;"><input type="radio" name="4" value="10" />No</li><br />
<li style="list-style-type:none;"><input type="radio" name="4" value="11" />I don't know</li><br />
</ul>
5. Is your total cholesterol under 200mg/dl and/or controlled by medication?<br /><ul>
<li style="list-style-type:none;"><input type="radio" name="5" value="12" />Yes</li><br />
<li style="list-style-type:none;"><input type="radio" name="5" value="13" />No</li><br />
<li style="list-style-type:none;"><input type="radio" name="5" value="14" />I don't know</li><br />
</ul><br />
<div><button type="submit" name="next" onclick="location.href='process-assessment.php?num=0&num1=5'" >Next</button></div><br /><br />
You have <b>83</b> out of <b>88</b> questions left<br /><br /></form>

 

And this is the closest I've come, but it's awkward, inefficient and incomplete.

 

function checkForm(){

elem = document.getElementById("myForm");
var x=document.getElementsByName("1");
var y=document.getElementsByName("2");
var z=document.getElementsByName("3");
        var group1 = false;
        var group2 = false;
        var group3 = false;


for(var i = 0; i < x.length; i++){
	if(elem.elements[i].checked == true){
		group1 = true;
	}
}

for(var i = 0; i < y.length; i++){
	if(elem.elements[x.length+i].checked == true && group1 == true){
		group2 = true;
	}
}

for(var i = 0; i < y.length; i++){
	if(elem.elements[x.length+y.length+i].checked == true && group1 == true && group2 == true){
		group3 = true;
		return true
	}
}

alert("Not Checked - stop");
return false;

}

 

So I'm looking for something more robust and efficient, but with the same basic funcionality.

Please help! :D

Link to comment
Share on other sites

Your biggest problem is that you have an onclick event for your submit button and it is scewing with the submit functionality. You don't need that in your submit button - remove it.

 

Second. Don't give the radio options names with just numbers. I did some testing and found that the fields are not referenced properly with numeric only names. Try using Q1, Q2, Q3, etc.

Link to comment
Share on other sites

Your biggest problem is that you have an onclick event for your submit button and it is scewing with the submit functionality. You don't need that in your submit button - remove it.

See that, changed it, no effect. Why is that an issue?

 

Second. Don't give the radio options names with just numbers. I did some testing and found that the fields are not referenced properly with numeric only names. Try using Q1, Q2, Q3, etc.

 

Can you elaborate?

 

Thanks for the help

 

** Actually, I've tried to create other mock forms to test on, with and without numbers (thats just a coincidence, after testing for a while I realized I should be using a number since the test does and thats when I switched) but maybe I'm not understanding and your elaboration can clear it up

 

 

Link to comment
Share on other sites

Your biggest problem is that you have an onclick event for your submit button and it is scewing with the submit functionality. You don't need that in your submit button - remove it.

See that, changed it, no effect. Why is that an issue?

 

Well, it has no effect if you don't fix the other problems too. But, it is a problem nonetheless. A form can be submitted by the user by clicking a submit button OR by pressing the enter key (depending where the focus is). The form already has an onsubmit trigger. That trigger will fire regardless of how the form is submitted. The onclick trigger in the submit button is

 onclick="location.href='process-assessment.php?num=0&num1=5'" 

So, assuming everything else is functioning correctly, if the user clicks the submit button, the onsubmit trigger is fired and validation is done. If validation fails then the form won’t submit. But THEN the onclick event in the submit button is triggered so the page will redirect to that URL – and not even submit the data. It is not needed and is detrimental to what you are trying to achieve. It needs to be removed.

 

Second. Don't give the radio options names with just numbers. I did some testing and found that the fields are not referenced properly with numeric only names. Try using Q1, Q2, Q3, etc.

Can you elaborate?

Well, I can tell you what the results of my testing were. When you have a single element, such as a text input you could reference the value using  formObject.Elements[textFieldName].value When you have a radio group you give all elements the same name. So, Javascript sees them as an array and to reference a particular radio button you would need to use: formObject.Elements[radioFieldName][radioElementIndex].value.

 

In my testing I tried alerting formObj.elements[1].length. That SHOULD have alerted with “3” because the radio group with the name “1” is an array of three elements. But, instead I received “undefined”. I spent a lot of time scratching my head and trying different things. Although the “1” is valid for an HTML field name, many programming languages do not allow variable name to being with a numeric character. So,  I changed the name of the radio inputs to “Q1” and then my test ran successfully.

 

Here is a working page:

<html>
<head>

<script type="text/javascript">

function checkForm(formObj, firstNo, lastNo)
{
    var errors = new Array();
    //Cycle through each question
    for(var qIdx=firstNo; qIdx<=lastNo; qIdx++)
    {
        var groupObj = formObj['Q'+qIdx];

        //Cycle through each answer to see if one is checked
        var hasAnswer = false;
        var answerLength = groupObj.length;
        for(aIdx=0; aIdx<answerLength; aIdx++)
        {
           hasAnswer = groupObj[aIdx].checked;
            if(hasAnswer) { break; }
        }

        if(!hasAnswer)
        {
            errors[errors.length] = ' - Question ' + qIdx + ' has not been answered.';
        }
    }

    if(errors.length>0)
    {
        var errorMsg = 'The following errors occured:\n\n';
        errorMsg += errors.join('\n');
        alert(errorMsg);
        return false;
    }

    return false;
}
</script>
</head>

<body>

<form id="myForm" action="process-assessment.php?num=0&num1=5" method="post" onsubmit="return checkForm(this, 1, 5);">
1. How many beers can a person have while eating dinner, and still be able to drive?<br /><ul>
<li style="list-style-type:none;"><input type="radio" name="Q1" value="1" />1-3</li><br />
<li style="list-style-type:none;"><input type="radio" name="Q1" value="2" />4-6</li><br />
<li style="list-style-type:none;"><input type="radio" name="Q1" value="3" />None</li><br />
</ul>
2. Whether or not you drink every day, are there times you drink more than 5 drinks in one sitting?<br /><ul>
<li style="list-style-type:none;"><input type="radio" name="Q2" value="4" />Yes</li><br />
<li style="list-style-type:none;"><input type="radio" name="Q2" value="5" />No</li><br />
</ul>
3. In the past six months, have there been days when you have had to cut down or limit your usual activities because of your health?<br /><ul>
<li style="list-style-type:none;"><input type="radio" name="Q3" value="7" />Yes</li><br />
<li style="list-style-type:none;"><input type="radio" name="Q3" value="8" />No</li><br />
</ul>
4. Is your blood pressure greater than 120/80 mmHg?<br /><ul>
<li style="list-style-type:none;"><input type="radio" name="Q4" value="9" />Yes</li><br />
<li style="list-style-type:none;"><input type="radio" name="Q4" value="10" />No</li><br />
<li style="list-style-type:none;"><input type="radio" name="Q4" value="11" />I don't know</li><br />
</ul>
5. Is your total cholesterol under 200mg/dl and/or controlled by medication?<br /><ul>
<li style="list-style-type:none;"><input type="radio" name="Q5" value="12" />Yes</li><br />
<li style="list-style-type:none;"><input type="radio" name="Q5" value="13" />No</li><br />
<li style="list-style-type:none;"><input type="radio" name="Q5" value="14" />I don't know</li><br />
</ul><br />
<div><button type="submit" name="next">Next</button></div><br /><br />
You have <b>83</b> out of <b>88</b> questions left<br /><br /></form>

</body>
</html>

 

Link to comment
Share on other sites

Well, it has no effect if you don't fix the other problems too. But, it is a problem nonetheless. A form can be submitted by the user by clicking a submit button OR by pressing the enter key (depending where the focus is). The form already has an onsubmit trigger. That trigger will fire regardless of how the form is submitted. The onclick trigger in the submit button is

 onclick="location.href='process-assessment.php?num=0&num1=5'" 

So, assuming everything else is functioning correctly, if the user clicks the submit button, the onsubmit trigger is fired and validation is done. If validation fails then the form won’t submit. But THEN the onclick event in the submit button is triggered so the page will redirect to that URL – and not even submit the data. It is not needed and is detrimental to what you are trying to achieve. It needs to be removed.

 

I get what you're saying

 

Well, I can tell you what the results of my testing were. When you have a single element, such as a text input you could reference the value using  formObject.Elements[textFieldName].value When you have a radio group you give all elements the same name. So, Javascript sees them as an array and to reference a particular radio button you would need to use: formObject.Elements[radioFieldName][radioElementIndex].value.

 

In my testing I tried alerting formObj.elements[1].length. That SHOULD have alerted with “3” because the radio group with the name “1” is an array of three elements. But, instead I received “undefined”. I spent a lot of time scratching my head and trying different things. Although the “1” is valid for an HTML field name, many programming languages do not allow variable name to being with a numeric character. So,  I changed the name of the radio inputs to “Q1” and then my test ran successfully.

 

I understand that too  :o

 

Thanks. I'm going to look at that and see if I can make something work. Thanks for the response and patience :)

Link to comment
Share on other sites

I tried that code, and it throws the error if I miss a question---perfect.

 

The issue I encounter is that it doesn't do anything if they are all checked (as in it doesn't seem to be submitting). Any ideas?

 

Thanks

Link to comment
Share on other sites

The issue I encounter is that it doesn't do anything if they are all checked (as in it doesn't seem to be submitting). Any ideas?

 

Um yeah. For testing purposes I didn't want the form to submit even if validation passed. So, I had a "return false;" even for the success scenario and forgot to change it when done. Just change the very last line in the function to "return true;". I'd also put a comment above that line to the effect "//No errors"

 

I should also point out that I change the functin to take three parameters - the form object (which is passed by simply including 'this' in the trigger call), the first question number and the last question number. You will need to set those two values on every page inthe onsubmit trigger call based upon the questions being displayed on the page.

Link to comment
Share on other sites

 

Um yeah. For testing purposes I didn't want the form to submit even if validation passed. So, I had a "return false;" even for the success scenario and forgot to change it when done. Just change the very last line in the function to "return true;". I'd also put a comment above that line to the effect "//No errors"

 

 

I figured it was something like that, was testing each one, but saw you replied. Thanks. Works perfectly.

 

The numbers are generated by the php script, so num and num1 are always going to contain the next set of numbers. I'll just throw those variables in there.

 

Thanks man, so far this is perfect. If it's not a big deal Im going to wait to mark it solved until I get it into the real code and working properly, but I don't forsee any issues.

 

Thanks again man, it would have taken me a generation to figure it out. You are a gentleman and a scholar :D

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.   Restore formatting

  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.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.