简体   繁体   中英

Selecting next radio button from selected one

I have a radio button group and I want to select the one next to the selected one.

 $(document).ready(function() { $('.next').click(function() { $("input[name=choice]:checked").next().click(); }); }); 
 .button { display: inline-block; padding: 1em; margin: 20px; border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" id="choise_1" name="choice" checked="checked" /> <label for="choise_1">One</label> <input type="radio" id="choise_2" name="choice" /> <label for="choise_2">Two</label> <input type="radio" id="choise_3" name="choice" /> <label for="choise_3">Three</label> <div class="button next">SELECT NEXT</div> 

This is what I have but it is not working

try this fiddle (just ensure that next() is called twice since there is a label between two checkboxes)

$('.next').click(function() {
  $("input[name=choice]:checked").next().next().click();
});

next() just gets the immediately following sibling.

The next element in tree is label , so you need to use next() twice to get next radio button

The change in the code is that you don't have to trigger click to check the radio s, instead you can change the property checked with .prop() method.

You need .nextAll(':radio:first') :

Description: Get all following siblings of each element in the set of matched elements, optionally filtered by a selector .

Here .nextAll(filter) with this method you don't have to worry about if your design changes or you add another element in the list. It will always target the :radio s only till it shares the same parent.

 $(document).ready(function() { $('.next').click(function() { $("input[name=choice]:checked").nextAll(':radio:first').prop('checked', true); }); }); 
 .button { display: inline-block; padding: 1em; margin: 20px; border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" id="choise_1" name="choice" checked="checked" /> <label for="choise_1">One</label> <input type="radio" id="choise_2" name="choice" /> <label for="choise_2">Two</label> <input type="radio" id="choise_3" name="choice" /> <label for="choise_3">Three</label> <div class="button next">SELECT NEXT</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM