views:

87

answers:

2

How can I validate radio buttons? Because this won't work at all. The radio button name and ID is billable and their value is either yes or no.

function formValidator() {  
  var errors = new Array();   

  if($("#billable").checked == false) {  
    errors[0] = "*Billable - Required";  
  }

  if(errors.length > 0) {  
    var error_msg = 'Please review:';  

    for(i=0;i<errors.length;i++) {  
      if(errors[i]!=undefined) {  
        error_msg = error_msg + "\n" + errors[i];  
      }  
    }  

    alert(error_msg);  

    return false;  
  }

  return true;  
}
A: 

Change to

$("#billable:checked").size()

Using $("#billable").checked you will get undefined, because this property doesn't exist. With $("#billable:checked").size() you will get how many checked radios do you have (0 or 1)

See in jsfiddle.

Topera
He's asking for JavaScript, not jQuery.
Gert G
He's using jquery....look the question `$("#billable")`
Topera
It's radio button not checkbox
anonymous123
A: 

if you try sometime with the JQuery validation plugin, all you will need is something like:

rules: {
'billable[]':{ required:true }
}

Edited:

as this post, this will help you:

var iz_checked = true;
$('input').each(function(){
   iz_checked = iz_checked && $(this).is(':checked');
});
if ( ! iz_checked )
Garis Suero
Okay, but even though I've chosen a radio button already, it will still alert.
anonymous123
please see edited answer...
Garis Suero
Here's part of the form: <td><?php if ($billable == "yes") {?> <input type="radio" name="billable" id="billable" value="yes" checked /> Yes<input type="radio" name="billable" id="billable" value="no"/> No<?php } else if ($billable == "no"){?><input type="radio" name="billable" id="billable" value="yes"/> Yes<input type="radio" name="billable" id="billable" value="no" checked /> No<?php }else{ ?><input type="radio" name="billable" id="billable" value="yes"/> Yes<input type="radio" name="billable" id="billable" value="no"/> No <?php } ?> </td>
anonymous123
Sorry for not placing spaces but it's just short so i think it's understandable. thanks!
anonymous123