Jonathan Weber Jonathan Weber - 4 months ago 26
jQuery Question

jQuery select next radio-button in matched radio-buttons

I am currently struggeling with jQuery since I feel there are concepts lacking that I am used to from languages like PHP or C. I can't (yet) handle to find sufficient replacements so I could need a bit of support.

What I want to do is to simply check the next radio button in a jQuery list of matched radio buttons.
Background: Those radio-buttons are hidden through CSS, but each button represents one image, that is shown via HTML/CSS, when the specific radio button is checked.

Here is what I got so far:

var imageRadios = $('input[type="radio"][name="image-select"]');

function nextImage() {
var nextImage = imageRadios.filter(':checked').eq(0).prop('checked', false).index(imageRadios) + 1;

imageRadios.eq(nextImage).prop('checked', true);
}


On pageload, the first radio-button is checked hard-coded (
<input ... checked>
).
nextImage()
is called every 20 seconds by a timeout. The first call of
nextImage()
works fine (next radio-button is checked), but when it is called the second time, it unchecks the second radio button and checks the first one again. This toggling between first and second radio button happens endlessly.
console.log(nextImage);
after the first function-line gives either
1
or
0
.

Thanks in advance for help with this approach or a broad hint to any other approach!




Note: I know, that this function does not yet handle the jump from last to first element, once the end of the list is reached.




Edit 1: The relevant HTML (dynamically generated by PHP), as asked for:

<input type="radio" name="image-select" id="image-0" checked>
<div class="image">...</div>

<input type="radio" name="image-select" id="image-1">
<div class="image">...</div>

<input type="radio" name="image-select" id="image-2">
<div class="image">...</div>

<input type="radio" name="image-select" id="image-3">
<div class="image">...</div>

...





Edit 2: JSFiddle as requested: https://jsfiddle.net/y7p7L68b/

Answer

var imageRadios = $('input[type="radio"][name="image-select"]');

function nextImage() {
    var nextImage = imageRadios.filter(':checked').prop('checked', false);
		var ind = imageRadios.index(nextImage);
    ++ind;
    if(ind >= imageRadios.length)ind = 0;
    imageRadios.eq(ind).prop('checked', true);
}

setInterval(nextImage, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="image-select" id="image-0" checked>
<div class="image">1...</div>

<input type="radio" name="image-select" id="image-1">
<div class="image">2...</div>

<input type="radio" name="image-select" id="image-2">
<div class="image">3...</div>

<input type="radio" name="image-select" id="image-3">
<div class="image">4...</div>