It has always bugged me that when I click cancel in an AjaxControlToolkit ModalPopup that any input fields are not cleared. If you click the the button that causes the popup again, the fields still contain any data that was entered prior to the initial cancel.
Demo | Download
I have come up with two ways to clear the input fields:
- Clear all fields on the form using an HTML reset button.
- Use jQuery to reset the values of the inputs in the popup only.
When using the ModalPopup control you have to set the CancelControlID property to the control that causes the cancel action. I first tried adding a runat="server" attribute and id to my html reset button so that the modal popup could find the button. This worked fine as far as the ModalPopup was concerned, but the reset action no longer worked. To get things working I ended up hiding a standard ASP.NET button control that the ModalPopup referred to. I then added a normal HTML reset button with a click event that triggered the the hidden button's click event. The code for the two buttons is below:
<asp:Button ID="ButtonCancelFormReset" runat="server" Text="Cancel" CausesValidation="false" style="display:none;" />
<button type="reset" onclick="document.getElementById('ButtonCancelFormReset').click();">Cancel</button>
The jQuery reset is pretty straight forward. When the cancel button is clicked all of the text type inputs have their value set to "".
<script type="text/javascript">
$(document).ready(function() {
$("#ButtonCanceljQueryReset").click(function() {
$(".jqueryReset >tbody >tr >td >input:text").each(function() {
$(this).val("");
});
});
});
</script>
Note: I am just dealing with text boxes in this example but it is certainly possible to find any other control types and rest them to defaults as well. You just have to get your jQuery selectors right.
Be sure to checkout the demo and download for the full code of the demo.
[dzone]