javascript - 'this' refers to wrong dynamically generated element in jQuery on() -


as part of dynamic form have checkbox field enables , disables next input field (they pair, when add new section form, checkbox , input field both added together).

.form-element   .checkbox     = f.label :foo_bool_field       = f.check_box :foo_bool_field, class: 'foo-bool-field-form-toggle'       .desc_foo_bool_field= "text describing field"    .input     = f.label :bar_input_field     = f.text_field :bar_input_field, disabled: f.object.foo_bool_field 

and it's in .form class block.

here code disabling

$('.form').on('change', '.foo-bool-field-form-toggle', function(e) {   // disabling code goes here }); 

if add few of these form elements, click on text "text describing foo_bool_field", enables/disables input form of first set only. if throw debugger above form disabling code , check this, this returns first set. if click text box □, works properly, disabling check boxes , referring right this of checkbox clicked on.

any ideas? i've tried few different things (click instead of change, etc), comes fact when clicking on text, this not element clicked on, , can't seem past that.

unlike languages, this in javascript refers parent calling object, can depending on context.

long story shory, try wrapping this in jquery selector so:

$('.form').on('change', '.foo-bool-field-form-toggle', function(e) {   // disabling code goes here   $(this).whatever }); 

basically, $(this) refer dom element triggered callback event (i.e. change), , work click or other event trigger.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -