-1

I'm trying to get all the radio buttons by their names and check if they are blank. If one is blank, then form will show an alert and will not submit. If all buttons are filled then it will go to the "else" part and see whether the answer is correct. If it is correct, then it will show the right values in that page <div>.

It goes to the "alert" but, even if I select the radio button, it does not go to else part.

What am I doing wrong?

$(document).ready(function() {
  $("#btnDel").click(function() {
    var count = 0;
    if ($("input[name='ques1']").attr('checked', false) || $("input[name='ques2']").attr('checked', false)) {
      alert("Please Fill all the Fields");
    } else {
      //question no 1                           
      if ($("input[name='ques1']").attr('checked', false) || $("input[name='ques2']").attr('checked', false)) {
        alert("Please Fill all the Fields");
      } else {
        if ($("input[name='ques1']:checked").val() == 6) {
          count++;
          $("#answerques1").text("Your Answer is correct");
        } else {
          $("#answerques1").html("<p style='color:red'>Your Answer is incorrect</p>");
        }
        //question no 2
        if ($("input[name='ques2']:checked").val() == 4) {
          count++;
          $("#answerques2").text("Your Answer is correct");
        } else {
          $("#answerques2").html("<p style='color:red'>Your Answer is incorrect</p>");
        }
      }
    }    
  });
});
showdev
  • 28,454
  • 37
  • 55
  • 73
Manjot
  • 67
  • 1
  • 9

2 Answers2

0

You can use .is(':checked') to check if radio button is checked or not..

    if(!$("input[name='ques1']").is(':checked')  || !$("input[name='ques2']").is(':checked')){
    // Both are not checked
    } 
ssilas777
  • 9,672
  • 4
  • 45
  • 68
  • hi sssilas777 this is not working.. I tried.. what else i can do... i want if they are not checked then to show alert.. please fill all the fields. – Manjot Aug 07 '15 at 19:13
  • Why it is not working.. any errors? can you create a jsfiddle? – ssilas777 Aug 07 '15 at 19:15
  • Sorry sssilas777 .. this works... now.. My mistake.. It is working perfectly.. none other worked... thanks a lot.. i was doing this fiddler for hours . now. – Manjot Aug 07 '15 at 19:24
0

Change all of the instance you are trying to check the radio buttons checked property to the following code.

if (!$("input[name='ques1']").is(':checked'))

Doing it like you currently are `.attr('checked', false)' sets the property instead of reading it.

mituw16
  • 5,126
  • 3
  • 23
  • 48