Search code examples
jqueryradiobuttonlist

How to check radio buttons values and if else..?


I need to check the values for a list of radio buttons and a select. Both a radio button and a select value can NOT be selected at the same time.

I have this now but it only works if I select the 1 radio button in the list of radio buttons. userdevice is a radio button list. And tags is the select.

var isChecked = $('input[name=userdevice]').prop('checked');
    if (isChecked) {
    var userdevice=$('input[name="userdevice"]:checked').val();
    }else{
    var userdevice="";
    }

    var tags=$('select[id=tags]').val()

     if ((userdevice.length > 0) && (tags.length < 1)){
    //if userdevice - a radio button is selected - run this...and this only works if the first radio button is selected...

     }else if((userdevice.length < 1 ) && (tags.length > 0)){
    //if a tag in the select is selected - run this... 

     }else {
    //if both user device and tags are not selected, then run this....
    }

Any input really appreciated, thanks!


Solution

  • You need to change prop('checked'); into:

    var isChecked = $('input[name=userdevice]').is(':checked');

    I tested. Result of isChecked was always false.

    Full code:

    var isChecked = $('input[name=userdevice]').is(':checked');
    if (isChecked) {
      var userdevice = $('input[name="userdevice"]:checked').val();
    } else {
      var userdevice = "";
    }
    var tags = $('select[id=tags]').val()
    if ((userdevice.length > 0) && (tags.length < 1)) {
      //if userdevice - a radio button is selected - run this...and this only works if the first radio button is selected...
    } else if ((userdevice.length < 1) && (tags.length > 0)) {
      //if a tag in the select is selected - run this... 
    } else {
      //if both user device and tags are not selected, then run this....
    }