Validate RadioButton with jQuery

3

I would like to do a validation via jQuery, to see if the client selected some RadioButton

JSFiddle Demo

It displays an alert if it has not been selected, but it still submits, should not.

HTML

 <table id="RadioButtonList1" cellspacing="15" cellpadding="15">
    <tr>
        <td><input id="RadioButtonList1_0" type="radio" name="RadioButtonList1" value="1" /><label for="RadioButtonList1_0">opc 01</label></td>
    </tr><tr>
        <td><input id="RadioButtonList1_1" type="radio" name="RadioButtonList1" value="2" /><label for="RadioButtonList1_1">opc 02</label></td>
    </tr><tr>
        <td><input id="RadioButtonList1_2" type="radio" name="RadioButtonList1" value="3" /><label for="RadioButtonList1_2">opc 03</label></td>
    </tr><tr>
        <td><input id="RadioButtonList1_3" type="radio" name="RadioButtonList1" value="4" /><label for="RadioButtonList1_3">opc 04</label></td>
    </tr><tr>
        <td><input id="RadioButtonList1_4" type="radio" name="RadioButtonList1" value="5" /><label for="RadioButtonList1_4">opc 5</label></td>
    </tr>
</table>
<input type="submit" name="Button1" value="Votar" id="Button1" class="btn btn-primary" />

JS

 jQuery(function(){
    jQuery('#Button1').bind('click',checkRadio);
 })

 function checkRadio() {
    var isChecked = jQuery("input[name=fileType]:checked").val();
    var booleanVlaueIsChecked = false;
    if (!isChecked) {
        booleanVlaueIsChecked = true;
        alert('Selecione algum logotipo');
    }
 }
    
asked by anonymous 30.06.2014 / 19:31

2 answers

2

You can put return false after alert :

jQuery(function(){
   jQuery('#Button1').bind('click',checkRadio);
});

function checkRadio() {
   var isChecked = jQuery("input[name=RadioButtonList1]:checked").val();
   var booleanVlaueIsChecked = false;
   if (!isChecked) {
       booleanVlaueIsChecked = true;
       alert('Selecione algum logotipo');
       return false;
   }
}

There is one more error in the script, the field name

var isChecked = jQuery("input[name=fileType]:checked").val();

Change to

var isChecked = jQuery("input[name=RadioButtonList1]:checked").val();

JSFiddle

    
30.06.2014 / 19:43
1

Test like this:

 jQuery(function () {
     jQuery('#form1').on('submit', checkRadio);
 })

 function checkRadio() {
     var isChecked = jQuery("input[name=fileType]:checked").val();

     var booleanVlaueIsChecked = false;
     if (!isChecked) {
         booleanVlaueIsChecked = true;
         alert('Selecione algum logotipo');
         return false;
     }
 }

link

The difference is that now I listen to submit of the form and in case of error I do return false;

    
30.06.2014 / 19:40