简体   繁体   中英

Why do my input elements not retain focus/blur events after postback?

I am using jQuery to set the focus/blur events of some input textbox controls via

$(function() {
  ..
});

But whenever a postback occurs, my controls no longer perform these events. I tried removing them from the document ready event and placing the code at the bottom of document, hoping it would load it each time, but that didn't work. How can I get these controls to retain there focus/blur events after postbacks?

Didn't think it mattered, but these postbacks are taking place in an ajax:UpdatePanel

You are attaching the events once to the elements, and they are removed later which means the events are also removed. You could attach the events again and again but you can simply attach the events to a higher level parent node and not worry about it:

$(function () {
    $(document).on('focusin', 'input.userTxtA_center', function () {
            this.value = '';
            this.className = 'userTxtB_center';

    });
});

I am using the focusin event instead of focus because focus doesn't bubble.

Isolated demo: http://jsfiddle.net/TUqsE/

Bind your methods using .live()

$('selector').live('EVENT', function() { });

Where EVENT is blur / focus /etc... Then it won't matter when your controls are created in the DOM, jQuery will automatically re-hookup the handler.

http://api.jquery.com/live/

OR Re-connect the events after the postback is complete

See - ASP.NET - UpdatePanel and JavaScript - for how to do it.

yes, it is because the updatepannel, use this pageload event instead of $(document).ready or $(function() {});

exmaple:

<script type="text/javascript" language="javascript">
    function pageLoad() {
       $('#MyId').bind("mouseover", function(e) {
           // Do something exciting
       });
    }
    </script>

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