jQuery .find(selector) troubles when selecting ajax.net element

989 Views Asked by At

I'm trying to find an ajax.net extender element with a dynamically generated ID. I'm trying to wire up an event handler to close all ajax.net modal popups when 'escape' is pressed. I'm confused why one of these works and one does not.

$find('ctl00_MainContent_ucUserControl1_mpePopup'); //returns the element
$find('[id="ctl00_MainContent_ucUserControl1_mpePopup"]'); //returns null

The ultimate goal is to be able to find the element without hard wiring the ID into the selector:

$find('[id$="_mpePopup"]');  //return all elements that end with "_mpePopup"
2

There are 2 best solutions below

0
On

I see now that there's a difference between $find and .find(). I hadn't realized that, but once it was mentioned that $find() was an MS Ajax shortcut, I looked deeper and found a solution that joins jQuery with MS Ajax.

var popups = $.grep(Sys.Application.getComponents(),
                function (elem, index) {
                    return $(elem).attr('_name') == 'ModalPopupBehavior';
                }
            );
$(popups).each(function () { this.hide(); });

The issue is $find(id) simply returns the element at Sys.Application._components[id]. 'id' is an index in this case, so you can't use a partial string or pattern.

Once you convert that collection into an array though, you can use jQuery.grep() on it to return an array of elements that satisfy some condition (in this case I noticed that '_name' was even easier to use than an attribute selector) and iterate through them with jQuery.each().

3
On

I believe you'll find that the $find operation requires a single ID. Unless I am grossly mistaken, there is no pattern matching capability in it. (For additional information on $find and $get, see http://mattberseth.com/blog/2007/08/the_everuseful_get_and_find_as.html)

You might consider populating a JavaScript variable with the known popup client ID, using the ever-helpful <%= mpePopup.ClientID %> page literal binding syntax or some other method convenient to your situation. Below is a simple example of ASPX markup, where mpePopup is a member of the page class:

<script type="text/javascript">
    function closePopup() {
        var mpePopupID = '<%= mpePopup.ClientID %>';
        var mpePopupBehavior = $find(mpePopupID);
        // ...
    }
</script>