However, for knocking together a UI for an intranet app, where you have gallons of network capacity (or is it measured in fathoms, can't remember) and can dictate the browser that will be used, it's not so bad - mainly cos it does a lot for little input. Which I do like.
I have a scenario in an intranet app where I want to show a modal popup after validating certain conditions in server-side code; and within this popup, I want to do some jQuery Ajax.
Following the quick'n'dirty approach, I used an AjaxControlToolkit ModalPopupExtender (no sniggering at the back) to show the popup. All good so far - popup appears and disappears.
Within the popup, I wanted the user to be able to search for products by name & category, and select from a list returned, closing the modal as they do so. Here's the script I was trying to attach: -
$(document).ready(function () { $("#btnSearch").click(function () { $.getJSON("itemSearchHandler.ashx", { "categoryID": $("#cboSearchCategory option:selected").val(), "term": $("#txtSearchProductName").val() }, handleResult ); }); // etc
Trouble is, this handler didn't fire, and I should have guessed as to why not, but h/t to Epic Phil for the solution.
The reason the event doesn't fire is because the DOM elements I am trying to reference don't exist when $(document).ready fires. They are dynamically added by ASP.NET Ajax when the Modal is displayed. jQuery tries to attach a handler and gives up when it can't find the element I'm asking to attach my script to - btnSearch - in the DOM.
Fortunately there is a way around this, and that's to use the .live method: -
$(document).ready(function () { $("#btnSearch").live('click', function () { $.getJSON("itemSearchHandler.ashx", { "categoryID": $("#cboSearchCategory option:selected").val(), "term": $("#txtSearchProductName").val() }, handleResult ); }); // etc
This will attach a handler to the event for all elements which match the current selector, now and in the future.
Handy !
Other thoughts ?
- ASP.NET 4's ClientIDMode="static" is a life-saver for working with jQuery
- The standard ASP.NET button control refuses to fire a Click event if it's assigned to the Ok or Cancel controls in a ModalPopupExtender. Use a standard html button (not an input type="button")
- I feel a bit dirty using ASP.NET Ajax as I've railed against it before and rightly so - here, here and here you go - but as I said, I'm knocking out a fast-turnaround intranet application not an eBay clone
- That's enough for now
No comments:
Post a Comment