Guys, I need help. There are several inputa with type "radio button". Is it possible to make the input switch using the "forward" and "back" buttons (div)? Those. to make it so that when you click on "forward", the checked attribute is passed to the next input, and when you click on the "back" button, the checked attribute is passed to the previous input. Simply put - switch radio buttons with div.btn-next and div.btn-prev. Thanks in advance!
- Yes, you can do it! - Grundy
- Can you tell me how? - Victor
- you need to use javascript: you find the current active radio button, and depending on the button you press, you are looking for the previous or next radio button and you make it active. - Grundy
- I would have the code ((I myself will not write it, I'm still a beginner - Victor
- then you should refer to the directory of language. for example MDN - Grundy
|
1 answer
$('#prev').on('click', function() { switchRadio(-1, getCheckedRadio()) }); $('#next').on('click', function() { switchRadio( 1, getCheckedRadio()) }); function switchRadio(direction, index) { var inputArr = $('input').toArray(); inputArr[index].checked = false; var targetIndex = index + direction; if (targetIndex < 0) { targetIndex = inputArr.length - 1; } else if (targetIndex > inputArr.length - 1) { targetIndex = 0; }; inputArr[targetIndex].checked = true; }; function getCheckedRadio() { var radioIndex; $('input').each(function( index ) { if (this.checked) {radioIndex = index}; }); return radioIndex; }; <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div><input type="radio" disabled>radioA</div> <div><input type="radio" disabled checked>radioB</div> <div><input type="radio" disabled>radioC</div> <div><input type="radio" disabled>radioD</div> <button id='prev'>prev</button> <button id='next'>next</button> - Synchronize the code in the snippet and on the fiddle, for they are different and there is a non-working code. - user207618 10:10
- corrected, thanks. - Vyacheslav Danshin
|