0

I have a radio element (8 elements with same name) and when I want to make anyone of them selected/checked I use the code:

myelmt.prop("checked",true)

The problem is that this code DOES NOT trigger the onchange event. Why? I always have to do this:

myelmt.prop("checked",true).trigger("change")

I have a libraary that listens to the change value of the radio, why the browser is not firing the onchange event when prop() is being used?

Jonas
  • 121,568
  • 97
  • 310
  • 388
Samul
  • 1,824
  • 5
  • 22
  • 47
  • Probably you are looking for this explanation: https://stackoverflow.com/questions/5874652/prop-vs-attr – Varit J Patel Dec 15 '17 at 21:34
  • because javascript does not trigger events only user actions do. – epascarello Dec 15 '17 at 21:42
  • @varit05 It has nothing to do with `prop` vs `attr`. No event is triggered for either function. – Barmar Dec 15 '17 at 21:48
  • @epascarello I am sorry to disagree, javascript DOES trigger events and recently you can even check if the event was cause by the user or by some js code BUT you can trigger it. – Samul Dec 16 '17 at 00:40
  • JavaScript has never called an event listener when you manually change a property or attribute. You always need to either call a function or trigger the event manually. – epascarello Dec 16 '17 at 00:43
  • @epascarello no, try this: add an event handler (using jquery for example) onkeydown of an input. Something like onkeydown -> console.log('HI');. Now, in you browser console, or using js in any button FIRE the keydown event like element.trigger("keydown") and you will see the event handler will be fired wheter you physicaly press a key in the input or if you fire the event manualy with js. – Samul Dec 16 '17 at 00:58

1 Answers1

0

I think JQuery documentation has the answer

For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

Additionally, this post may help

Jonathan Chaplin
  • 2,442
  • 1
  • 18
  • 21
  • I think for all element types, the event only occurs when the element is changed by the user, not by code. – Barmar Dec 15 '17 at 21:48
  • It does not explain why my change event is not being fired cause even if I click outside anywhere in the page (making the blur effect) the event does not get fired. – Samul Dec 16 '17 at 00:40
  • If you change it programmatically then click outside of it, the change was still not user initiated. – Erik Philips Dec 18 '17 at 17:35