简体   繁体   中英

change event doesn't fire on ajax loaded forms

I have an HTML document, with the jquery code

    $(function(){
[...]
     $("#newNotice").click(function(){
        $("#properties").load("testDiagramm.html #NoticeForm");
        return false;
       });
     function showFormValues(){
        var s = $("form").serialize();
        [... Do things ...]
     }
     $("input, textarea").change(showFormValues);
    });

At the beginning there is no form in the HTML document. But i load diffrent forms into the document. One of those request you can see here

$("#properties").load("testDiagramm.html #NoticeForm");

The problem is. that the codeline

$("input, textarea").change(showFormValues);

only fire, when the form was loaded at the beginning. What must I do, if i want to execute the function showFormValues(), when I changed something in the formular, which i load later?

Thanks a lot for your answers.

Lara

Your form loses its binding to the DOM after it is reloaded via ajax, so event handlers previously bound to the elements that get injected into the page are lost.

I would normally suggest using event delegation with live , but it does not support the change event, so a safe bet would be to rebind using a callback as a second parameter to your $.load function:

    $(function(){
[...]
     $("#newNotice").click(function(){
        $("#properties").load("testDiagramm.html #NoticeForm", function() {
            $("input, textarea").change(showFormValues);
        });
        return false;
       });
     function showFormValues(){
        var s = $("form").serialize();
        [... Do things ...]
     }
     $("input, textarea").change(showFormValues);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM