Maometto Maometto - 1 month ago 8
Javascript Question

Change checked radio button with button tag and js

I wanna change checked radio button with a click on another "button" element


html



<button onclick="slideMe(-1)"></button>
<input checked type="radio" name="slider" id="slide1">
<input type="radio" name="slider" id="slide2">
<input type="radio" name="slider" id="slide3">
<input type="radio" name="slider" id="slide4">
<input type="radio" name="slider" id="slide5">
<button onclick="slideMe(1)"></button>


JS



function slideMe(dir) {
var inputs, slides, i;
inputs = document.getElementsByName("slider");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked == true) {
inputs[i].checked = 0;
if (i > 0 && i < 7 || dir == -1) {
inputs[i + dir].checked = true;
break;
} else if (i = 0) {
inputs[8].checked = true;
break;
} else {
inputs[0].checked = true;
break;

}
}
}
}



here is a JsFiddle example

Answer

I changed your slideMe function.

First, I obtain index of current checked input and assign it to a variable(currIndex).

After that, according to value of dir I increase(if dir==1) or decrease(if dir== -1) value of currIndex. And apply additional conditionals.

function slideMe(dir) {
    var inputs, currIndex;
    inputs = document.getElementsByName("slider");

    for(var i=0; i<inputs.length;i++)
    {
        if(inputs[i].checked==true)
        {
          currIndex = i;
          inputs[i].checked = false;
        }
    }

    if(dir == 1)
    {
        currIndex++;

        if(currIndex == (inputs.length))
          currIndex = 0;
    }
    else
    {
        currIndex--;   

        if(currIndex == -1)
          currIndex = (inputs.length-1);
    }

    inputs[currIndex].checked = true;
}

JS Fiddle example.