kalls
kalls

Reputation: 2865

ASP.Button - OnClientClick firing incorrectly

I have a asp.net button and I am using OnclientClick to close the window

<asp:Button ID="btnCancelSomething" runat="server" class="type-button" 
                    Text="Cancel"  OnClientClick = "Javascript:self.close()" 
                    onclick="btnCancelSomething_Click"/>

the onclick event does nothing and I am planning to remove it. However, when I click the button the first time it is loading the page again. I click the button again then the script is fired.

How to make the window close the first time?

Upvotes: 0

Views: 881

Answers (1)

David
David

Reputation: 218960

If the button isn't going to have any server-side functionality behind it anyway, why make it an asp:Button at all? A regular button will do the trick just fine:

<input type="button" value="Cancel" class="type-button" onclick="self.close()" />

That way it's purely client-side, since that's all the functionality that's needed anyway. It won't cause any "post-back" unnecessarily.

You could even take it a step further and break apart markup from functionality:

<input type="button" value="Cancel" class="type-button" id="cancelButton" />

Then in a script tag elsewhere, or in a separate file:

$('#cancelButton').click(function() {
  self.close();
});

(Of course, this example assumes jQuery. But then what doesn't? The separation of markup and functionality if the key point here, though. How you achieve it, even how you identify the element with an id as in my example or some other way, is up to you.)

Upvotes: 4

Related Questions