
So basicially I have two functions. First function runs in case of I check a radio button that comes before the currently checked one. And the second function runs in case of I check a radio button that comes after the currently checked one. How could this be done?
<input type="radio" id="a" name="radio">
<label for="a">A</label>
<input type="radio" id="b" name="radio" checked>
<label for="b">B</label>
<input type="radio" id="c" name="radio">
<label for="c">C</label>
<input type="radio" id="d" name="radio">
<label for="d">D</label>
$("input[name='radio']").change(function(){
if {
// do something
}
if {
// do something
}
});
Check the index of the input before, if its less then fire the before function, else fire the after. then reset the current index to the now index.
var currentIndex = $("input[name='radio']:checked").index('input');
$("input[name='radio']").change(function() {
var index = $(this).index('input');
if (index < currentIndex) {
console.log('before');
} else {
console.log('after');
}
currentIndex = index;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="a" name="radio">
<label for="a">A</label>
<input type="radio" id="b" name="radio" checked>
<label for="b">B</label>
<input type="radio" id="c" name="radio">
<label for="c">C</label>
<input type="radio" id="d" name="radio">
<label for="d">D</label>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With