Skip to content
Advertisement

radio and select option with alert

how do i show alert if no radio button selected form two radio button and after that show alert on select option if not selected. but I am getting alert on both radio button how do I fix it

$('#form_id').submit(function(el) {
        el.preventDefault();
        let r = $('input[type=radio][name=name]').val();

        if(r != 'inst' ){
            alert('Please select radio')
            return false;
        }else if(r != 'hq'){
            alert('Please select radio')
            return false;
        }

        if('0' === $('#select_id').val()){
            alert('Please select option')
            return false;
        }else{
            this.submit();
        }
        

    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form_id">
    <input type="radio" name="name" id="r1" value="inst">
    <input type="radio" name="name" id="r2" value="hq">

    <select id="select_id" class="">
        <option value="0">--select--</option>
        <option value="6">Advertisements</option>
        <option value="4">Another reason:</option>
    </select>

    <button type="submit" class="btn btn-primary">submit</button>
</form>

Advertisement

Answer

The problem is that in your case, the 2 if statements regarding your radio buttons will always be false for one of the cases.

So do it like this.

let r = $('input[type=radio][name=name]:checked').length;

if (r == 0) {
  alert('Please select radio')
  return false;
}

Demo

$('#form_id').submit(function(el) {
  el.preventDefault();
  let r = $('input[type=radio][name=name]:checked').length;

  if (r == 0) {
    alert('Please select radio')
    return false;
  }
  if ('0' === $('#select_id').val()) {
    alert('Please select option')
    return false;
  }
  this.submit();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form_id">
  <input type="radio" name="name" id="r1" value="inst">
  <input type="radio" name="name" id="r2" value="hq">

  <select id="select_id" class="">
    <option value="0">--select--</option>
    <option value="6">Advertisements</option>
    <option value="4">Another reason:</option>
  </select>

  <button type="submit" class="btn btn-primary">submit</button>
</form>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement