0
votes

I've seen a few examples on how to do this but they don't seem to be working for me. Having said that, I am doing it a little differently than the examples I've seen so I'm not sure if what I'm trying to do is possible.

I have a multiline asp texbox and onclientclick I want to make sure (among other things) the user hasn't gone over on max length before I submit the onclick event. However, this textbox is part of a user control that will be used X number of times on the page so I can't just grab the control from the Javascript. I have to send the clientID from the code behind. So I'm adding the OnClientClick event on the codebehind and pass the clientID for the control there. I wonder if that's why I'm getting the results I'm getting.

SaveNoteButton.OnClientClick = string.Format("return BeforeSave('{0}');", NoteTextBox.ClientID);

<asp:Button runat="server" CssClass="casenotes-bluebuttons" ID="SaveNoteButton" Text="Save" OnClick="SaveNoteButton_Click" Enabled="false" />

    function BeforeSave(noteCtrl) {
        var txt = document.getElementById(noteCtrl);

        if (txt.value.length > 500) {
            alert("false");
            return false;
        }
        else {
            alert("true");
            return true;
        }
    }

So in theory, the OnClientClick property is added to the SaveNoteButton button. When it's fired, it passes the NoteTextBox.ClientID, the js checks the textbox length, returns true or false then the OnClick event fires depending on the return value. But it doesn't. I even tried wrapping the method call in an alert and the method is in fact returning what I expect but the OnClick event isn't firing regardless of the method's return value. I even tried removing the method call and hardcoding true and it still doesn't fire. So I know the return value is true and yet no OnClick love.

3

3 Answers

0
votes

Oddly enough, it was syntax on the call to the js method.

SaveNoteButton.OnClientClick = string.Format("return BeforeSave('{0}');", NoteTextBox.ClientID);

becomes

SaveNoteButton.OnClientClick = string.Format("BeforeSave('{0}')", NoteTextBox.ClientID);

and it works just fine.

0
votes

Remove the Enabled="false" bit. This is why the onclick event does not fire.

0
votes

Alright, this is what I did to solve the problem:

SaveNoteButton.OnClientClick = string.Format("if(!BeforeSave('{0}', '{1}')) return false;", NoteTextBox.ClientID, this._maxLength);