user3799115 user3799115 - 3 months ago 15
Javascript Question

jquery change something added by jquery

i have a problem with onchange event in jquery.
the event added dont work

This is my code:



<script>

jQuery("#select1").on('change',
function(event)
{
event.preventDefault();
jQuery.ajax({
type:'POST',
async: true,
cache: false,
url: '<?php echo Router::Url(array('controller' => 'XXX','admin' => TRUE, 'action' => 'onChangeSelect1Ajax'), TRUE); ?>',
success: function(response) {

jQuery('#select2Position').empty().append(response);

},
error: function(response) {

alert('error');
},
data:{ idselect1 : this.value }
});
return false;

}
);


jQuery("#select2").on('change',
function(event)
{
event.preventDefault();
jQuery.ajax({
type:'POST',
async: true,
cache: false,
url: '<?php echo Router::Url(array('controller' => 'XXX','admin' => TRUE, 'action' => 'onChangeSelect12Ajax'), TRUE); ?>',
success: function(response) {

jQuery('#other').empty().append(response);

},
error: function(response) {

alert('error');
},
data:{ idselect1 : jQuery("#select1").value, idselect2 : this.value }
});
return false;

}
);


</script>





When i'm change select1, select2 is added.
but select2 onchange event dont working.
could you help me please?

thanks

Answer

If you are adding select2 dynamically then you need to use event delegation technique to attach event to it as follows:

jQuery(document).on('change',"#select2",
            function(event)
            {       
              event.preventDefault();    
               jQuery.ajax({
                    type:'POST',
                    async: true,
                    cache: false,
                    url: '<?php echo Router::Url(array('controller' => 'XXX','admin' => TRUE, 'action' => 'onChangeSelect12Ajax'), TRUE); ?>',
                    success: function(response) {

                        jQuery('#other').empty().append(response);

                    },
                  error: function(response) { 

                    alert('error');  
                    },
                    data:{ idselect1 : jQuery("#select1").value, idselect2 : this.value }
                });
                return false;

            }
    );

I am sure it will solve your issue.