How to properly add <select> to a jquery page and let the change event work?

I currently have multiple selections on a page that is dynamically added via calls ajaxusing jquery.

The problem I am facing is that I cannot get the change event to work with the added selection unless I use onchangeinside the tag, for example.

<select id="Size" size="1" onchange="onChange(this);">

This works, but I'm wondering if there is a way to get it to be assigned to jquery. I tried to use $('select').change(onChange($(this));in the usual place $(document).ready, but it did not work.

I tried adding an event with bind after ajax call, but that didn't work either.

Is there a better way to schedule an event?

+4
source share
4 answers

I had a similar problem and found this solution here :

When you do something like this:

$('p').click( function() { alert('blah'); } ) 

All currently existing 'p' elements will have an attached click handler. Now, if you add other 'p' elements to the page, they will not be attached to them by your click handler. You would need to "restart"

$('p').click( function() { alert('blah'); } )

on new elements to attach handlers to them.

You might like to watch the LiveQuery Plugin as it manages all newly added elements so that they are previously attached handlers attached to them when they are added to the page.

Karl Rudd

So, after adding the selection, you will have to repeat the change () call.

+2
source

$( '') (OnChange ($ ()).

. JavaScript, , , , ..

, , onChange jQuery. . , jQuery, jQuery , .

-() - , . . , , :

$('select').change(onChange);
+7

:

$('#newSelect').change(
    function() 
    { 
        onChange(this)
    }
);

, , :

$('.classname').unbind("change");
$('.classname').change(
    function() 
    { 
        onChange(this)
    }
);
0
source

Thanks guys for the help, the answers worked, but not for what I did. I finally figured this out with firebug. I tried to assign a change event before ajax finished doing this (I'm new to this ajax stuff, as you may have noticed).

I added an event that assigns a callback to load (), and now everything works fine.

        $(this).load('ploc002.php', {JobNumber: JobNumber, Edit: this.id}, function()
        {
            // The DOM has been changed by the AJAX call
            // Now we need to reassign the onchange events
            $('select,input').change( function()
            {
                onChange(this)
            });
        });
0
source

Source: https://habr.com/ru/post/1697347/


All Articles