0

Is there a way to pass the event that caused a change event to the change event function? I basically have a method that programmatically clicks a radio button. This calls the change function and I need to know if the original click was done by a human or done programmatically.

// This will trigger a change event on both input names menu1 and menu2.
$("#menu1").on("click", function() {
    $("#menu2A").click();
});

$("input [name='menu1'], input [name='menu2']").on("change", function(e) {
    var inputName = $($(e)[0].target).attr("name");
    if (inputName === "menu2") {
      // This is where I want to check that the click event was initiated by a human.
    }
});

I tried creating a $("input[name='menu2'].on("click", function...) that calls e.preventDefault() to check the click event, but that didn't work. It hit the change function before it hit the click function. This is why I figured I needed to check the click event within the change event function.

L Becker
  • 685
  • 8
  • 28

2 Answers2

0

I don't have enough context to understand your end goals, but if you would prefer that the change event for menu2 is not triggered when clicking on menu1, you can modify how you are setting menu2 to be selected:

// This will trigger a change event on input name menu1 only, NOT menu2
$("#menu1").click(function() {
  $("#menu2").prop("checked", true);
});


$("input[name=menu1], input[name=menu2]").change(function(e) {
  var inputName = $(this).attr("name");
  console.log(inputName);
});

$("#clear").click(function() {
  $("input[name=menu1], input[name=menu2]").each(function() {
    $(this).prop("checked", false);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='radio' id="menu1" name="menu1">Menu 1
<input type='radio' id="menu2" name="menu2">Menu 2
<button id='clear'>Clear</button>
emshore
  • 489
  • 6
  • 15
0

I have noticed an even better answer here, using the event.originalEvent object: https://stackoverflow.com/a/6692173/2802014

Have you tried this?

var eventstore;
$("#menu2A").on('focus blur',function(e){
 if(e.which){
  eventstore='human';
 }
});

then you test if eventstore='human' inside of your "on change" (don't forget to set eventstore to 0 after that)

Richard
  • 994
  • 7
  • 26