Jump to content

[SOLVED] To validate radio button


lcy

Recommended Posts

Hi all.

 

I have some problems with radio buttons. Hope to get some help here. Thanks in advance.

 

Here's the html:

<?php while($row=mysql_fetch_array($result)) { ?>
         <input name="replacement" id="replacement" type="radio" 
            value="<?php echo  $row['date']; echo $row['title']; ?>"

 

I need to validate if none of the radio buttons is checked using javascript. How can I do that? Any help will be appreciated. =)

Link to comment
Share on other sites

The link provided is not helping.

 

The number of radio button here is not certain, depending on the result looped from database. I've tried something else using codes below. However, the message box displaying error pop out whenever I do not check the first radio button, which mean that I can just choose the first option.

 

function check(){

	var replacement = document.getElementById('replacement');

if (!replacement.checked) {
alert("Please fill in all the fields marked with *");
        replacement.focus();
return false;
        }
        }

 

This code is working actually. If anyone here know how can I modify this codes to make it works better, your help is appreciated? Thanks.

Link to comment
Share on other sites

Solved! Codes used as below

 

function validateCB(theName){
   var counter=0;
   var cb=document.getElementsByName(theName)
   for (i=0; i<cb.length; i++) {
        if((cb[i].tagName=='INPUT')&&(cb[i].type=='radio')){
          if (cb[i].checked)
             counter++;
        }
   }
   if (counter==0) {  
   return false;
  }
return true;
}

function check(){


if (!validateCB('replacement')) {
   		alert("Please fill in all the fields marked with *");
   		return false;
 }

         return true;
         }

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.