rawjellybeans
rawjellybeans

Reputation: 23

jquery checking radio input not working

Im having a problem trying to check a radio input using JQuery. I'm just starting to learn so bear with me.

I have 4 radio buttons that i want to be able to scroll through using clicks. The problem is i can only ever get the first if statement to work. Here's my html:

<a class="back"> < </a>
  <input type="radio" name="radio-control" id="radio-1" checked="checked"/>
  <input type="radio" name="radio-control" id="radio-2"/>
  <input type="radio" name="radio-control" id="radio-3"/>
  <input type="radio" name="radio-control" id="radio-4"/>
<a class="next"> > </a>

and my JQuery:

if($('#radio-1').is(':checked')) { 
  $('.next').click(function() {
    $("#radio-2").prop("checked", true)
  });
}
if($('#radio-2').is(':checked')) { 
  $('.next').click(function() {
    $("#radio-3").prop("checked", true)
  });
  $('.back').click(function() {
    $("#radio-1").prop("checked", true)
  });
}
});

Here it is on codepen: http://codepen.io/anon/pen/LpGOqq

If anyone could provide some input it would be much appreciated.

Upvotes: 1

Views: 1012

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82241

Checking checked state and then binding event is dirty way of doing this.

You can rather have simple click event for prev/next button where you target prev/next element of checked radio element and set it checked to true. like this:

$('.next').click(function () {
    $(":checked").next().prop("checked", true)
});
$('.back').click(function () {
    $(":checked").prev().prop("checked", true)
});

Working Demo

Upvotes: 1

Related Questions