Search code examples
jqueryselectdelegatesfocusin

select onfocusin do something is not working


I am trying to use AJAX to load some inputs & selects that shows up later on the page. I am doing something like this.

<input type='product' alt='2'/>

$("input[type='product']").on("focusin", function(){
    var product_type_ids = $(this).attr('alt');
    $(this).autocomplete({
        //  ajax load the information here
    }); 
});

<select type='product' alt='2'/>

$("select[type='product']").on("focusin", function(){
    var product_type_ids = $(this).attr('alt');
    // some codes here
});

the result is OK for select and inputs that exists from the beginning of the page rendering but not for elements that showed up later. Does anyone know what is happening here? thanks!


Solution

  • It's event delegation. Change your selector.

    $("body").on("focusin", "input[type='product']", function(){
    
    $("body").on("focusin", "select[type='product']", function(){
    

    This will allow the element's event to propagate to a static parent, such as 'body' in this case. Which will work for all future elements as well.