user3371339
user3371339

Reputation: 9

Trying to prevent submit until one radio button is selected using jquery

Must be a syntax error, because I can't even get my first alert

My submit button:

input type="submit" name="payOnline" id="payOnline" value="Pay Online" style="color: red; font-    weight: bold; width:100px; height:40px;"/> 

jQuery:

<script>
$("#payOnline").click(function() {

alert("submit button clicked on");
if ($("input:radio[name='epackage']:checked").val() <0 ) {
   alert('Nothing is checked!');
    return false;
   event.preventDefault(); 
}

else {
  alert('One of the radio buttons is checked!');
}
});
</script>

Upvotes: 0

Views: 1304

Answers (3)

partypete25
partypete25

Reputation: 4413

You want to change .val to .length. That will return a value of 0 or 1. then change the if to '<= 0'...

<form>
    <input type="radio" name="epackage" value="1">option 1<br>
    <input type="radio" name="epackage" value="2">option 2
    <input type="submit" name="payOnline" id="payOnline" value="Pay Online" style="color: red; font-weight: bold; width:100px; height:40px;"/> 
    </form>

$("#payOnline").submit(function() {
alert("submit button clicked on");
if ($("input:radio[name='epackage']:checked").length <=0 ) {
   alert('Nothing is checked!');
   return false; 
} else {
  alert('One of the radio buttons is checked!');
}

});

Upvotes: 2

Felix
Felix

Reputation: 38102

There's no syntax error here.

Some changes:

1) Pass event to your click function

2) Move e.preventDefault() out of your if condition.

3) Wrap your code inside DOM ready handler:

$(function() {
    $("#payOnline").click(function(event) {
        event.preventDefault();
        alert("submit button clicked on");
        if ($("input:radio[name='epackage']:checked").val() <0 ) {
            alert('Nothing is checked!');
            return false;
         }

         else {
             alert('One of the radio buttons is checked!');
         }
    });
});

Upvotes: 1

unsafe_where_true
unsafe_where_true

Reputation: 6300

1.) Make sure you have jQuery in one of your script tags (this might be obvious but one never knows), e.g.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

2.) Check that you have a "<" in front of your input tag, your code doesn't provide it:

<input type="submit" name="payOnline" id="payOnline" value="Pay Online" style="color: red; font-    weight: bold; width:100px; height:40px;"/>**

With these two issues in place, your code in fact runs just fine for me! The alerts show up.

Upvotes: 0

Related Questions