Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run different functions based on positioning

enter image description here

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
    }

  });
like image 930
Alexander Hein Avatar asked Apr 14 '26 11:04

Alexander Hein


1 Answers

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>
like image 72
BenG Avatar answered Apr 16 '26 00:04

BenG