Search code examples
javascriptjqueryevent-handlingdocument-readydynamic-html

Jquery selector and event listening logic?


I have just begin to studying Jquery for my current project. I am confused about selectors and listeners of Jquery objects.

$("input").change(function() {
  alert( "Handler for .change() called." );
});

This exact copy of http://api.jquery.com/change/ ... I changed the selector from ".target" to "input".

However none of input element are handled by change event.

I get this error. And i am pretty sure that there are elements with input name

"Uncaught TypeError: Cannot read property 'change' of null functions.js:378 (anonymous function)".

Is it something wrong with logic or is there a syntax error. I narrowed down the error this much but i still don't see the problem?

------EDIT------

I test the answers and all answers are right. When an event handler/listener assigned to elements via jquery selectors.

$("selectorStatement").EventHandlerShortCut(function() {
  //Some code
});

When below code executed

$("input").change // Change handler for ALL INPUT elements

Jquery engine get All the input elements ( !!All input elements that is declared and exist in that moment -the moment handler executed- !!)

After that moment if new element generated, Handler will not recognize that. The only thing that can prevent this is using $(document).ready which will call the code after whole document is created. As @Henrik Peinar , @Chandrika Prajapati , @G Z , @Gaurav , @Mzn Mentioned in their answers...

In addition to this, In my case,

I generate some inputs by using

document.anElement.innerHTML = "<foo></foo>"

Which is used after the document is ready. There can be 2 approach to this case.

This foo element can be generated while document is rendering. By using

display:none

So the element can be read by jquery engine when document is ready. And can be made visible when the comes.

Or.

$("fooSelector").handlerType(...

Handler caller can be called again again while page is dynamic. Which is a easy but a bad solution.


Solution

  • it sounds your selector return no results (null).

    to verify this function get called when the markup is ready execute the statement when the document is fully loaded.

    try use the following:

    $(function () {
    
    $("input").change(function() {
      alert( "Handler for .change() called." );
    });
    
    
    });
    

    $(function() { ...}) is equivilant to $(document).ready(function() { ...});