Checking for a single or multiple radio buttons

Hello, I have the following javascript code:

for (var i=0; i < myRadio.length; i++)  {
		if (myRadio[i].checked)  {
			myChecked = 1;			
		}
	}	
	if (myChecked == 1) {
		return true;	
	} else {
		alert("Choose one radio Button!");
		return false;
	}

This works fine when I have more than 1 radio button. However for just a single radio button it does not work. I don’t know how many radio buttons I will have since they are being created from a mysql query.

I’m very bad with javascript, so how should I amend the code so that it also works with only one radio button? I just need to check if they are trying to submit the form without selecting any radio buttons.

Thanks.

Try this:

for (var i=0; i < myRadio.length; i++)  {
        if (myRadio[i].checked)  {
			break;     
        } else {
        	alert("Choose one radio Button!");
    		break;
		}
}

The problem is, and I should have said this before, that when there is only 1 button, I get a javascript error saying that myRadio.length is undefined!

So I need know how are you setting myRadio.
Is myRadio something like

var myRadio = document.getElementsByTagName("input");

or what is it?

Here’s the whole thing:

function checkForm(myForm) {
	var myRadio = myForm.transChoice;
	var myChecked = 0; // initialize the variable we'll use to test for checks	
	for (var i=0; i < myRadio.length; i++)  {
		if (myRadio[i].checked)  {
			myChecked = 1;			
		}
	}	
	if (myChecked == 1) {
		return true;	
	} else {
		alert("Choose one radio Button!");
		return false;
	}
}

transChoice is the name of the radio buttons.

What is this?:

var myRadio = myForm.transChoice;

Have a look at:
Example: http://jsbin.com/uhefu/
Source: http://jsbin.com/uhefu/edit

I’m bad with javascript, this code was sent to me and it works for multiple buttons. But from what I understand:

myForm is the form itself, sent to the function by the onSubmit event. Then transChoice, like I said, is the name of the radio buttons. So myRadio should be a variable with the object for that radio button…

Weird!
Sorry! I’ve tried but am unable to figure out a fix.

When there is only one radio button, the myRadio variable will be the single string value for that radio button. When there are multiple radios buttons then myRadio will be an array of strings.

You need to make sure that myRadio is an array before it gets to the for loop.


if (!myRadio.length) {
    myRadio = [myRadio];
}

As usual Paul, you have the solution, thanks a million.

Hello again friends, things just got a little more complicated. Turns out the same form I am using to choose a default radio button now also needs to be used to save data (without choosing a radio button).

So I have 2 submit buttons, named differently and act upon the php code depending on which submit button they chose, the one for choosing a default via the radio buttons or the one for saving the data in the text field.

So the question is, how can I check which button they clicked on to submit the form and then trigger my radio button checking magic if it was that one, or not trigger anything at all if it was the other submit button.

Cheers.

You can give each submit button a name


<p>
    <input type="submit" name="add" value="Add">
    <input type="submit" name="save" value="Save">
</p>

Then you can check from PHP if those actions have been set


if (isset($_POST['add'])) {
    // do add stuff
}
if (isset($_POST['save'])) {
    // do save stuff
}

no, no that part I have already working, I mean in the javascript. I need the chooseDefault button to trigger the javascript check, but not the save button.

As you haven’t specified what html code you’re working with, I’ll make some assumptions that you’re doing things the right way.

I’ll assume that your form has a unique identifer, and that you are assigning events via javascript.

The sample HTML code is:


<form id="myForm">
    ...
    <p>
        <input type="submit" name="chooseDefault" value="Choose Default">
        <input type="submit" name="save" value="Save">
    </p>
</form>

When the form is submitted, you place code that related to both submit buttons in the standard onsubmit event for the form


form.onsubmit = function () {
    // code relating to both submit buttons here
}

For code that relates only to the one button, you assign that to the onclick event for that button itself.

For example, this allows the chooseDefault button to check if things validate(), and if successful it then triggers the form submit event.

The success values are retained and returned, in case a return value of false is required to prevent things from carrying on.


form.elements.chooseDefault.onclick = function () {
    var success = validate();
    if (success) {
        success = this.form.onsubmit();
    }
    return success;
}

In fact, on reflection I have realised that you can simplify things even further than that.

The chooseDefault onclick event automatically submits the form if it’s allowed, you you only need to return the false return from the validate function to prevent the from submitting.


var form = document.getElementById('myForm');
form.onsubmit = function () {
    // code relating to both submit buttons here
}
form.elements.chooseDefault.onclick = function () {
    return validate();
}

Not sure I fully understand. This bit of code doesn’t go in the header of the document, it goes elsewhere?

Right now the form element has this:

&lt;form id='MultiTranslations' method='POST' action='$self' onSubmit = 'return checkForm(this);'&gt;

So, you are correct, either button would trigger that checkForm() function.

Maybe I should just remove that and have the chooseDefault button trigger that function? Of course, in trying to do this, I have to rewrite the checkForm() function so that it identifies the whole form itself by ID since I won’t be able to do the checkForm(this) trick…

Ok, this seems to have done the trick, now why didn’t I think of that before?

I replaced function form as follows:

function checkForm() {
	var myRadio = document.getElementById('MultiTranslations').transChoice;

...

and then this function only gets called by the onClick method of the chooseDefault button.

Seems to work. I have no other validation at the moment, when they hit the other submit button, but if I did, I guess I could just put another function to be called by that button the same way, in the onClick method.

Sound right?

Yes, preferably these scripts are placed just before the </body> tag. It’s a common practice now, which both speeds up the page loading, and allows you to easily attach events on to page elements.

Using inline scripting events is a big no-no, as they tend to be harder to maintain. In a similar way, in-page CSS is best moved up to a centralised place near the start of the head.

Hello again,

Things have, of course, evolved now. Customer now wants an empty text field that people can, if they wish, fill out and choose as default.

So now I need code to make the radio button for that field only be selectable if it is not empty. That would be great. Failing that, since it sounds quite complicated, I would need code to check that if the radio button that corresponds to that field is checked, then that field cannot be empty.

But, now that I think about it, this won’t work because if the field is empty, meaning there is no value, then I can’t make that value the default because it is not in the database yet, so I don’t have a key for it. Of course, I could always do some PHP magic that if the radio button that was checked does not have a key in it (the radio button values are the key for that entry in the DB) then we know they are choosing the new value, so assign it to the DB, get a key and put that into the default.

Could be.

Sorry for the rambling, does that make sense? I know this is not the PHP forum, so I’m not asking for help with that bit, I’ll figure it out, but I’m including it here just in case I’m being undercaffeinated and stupid.