Ramin Asadi
Ramin Asadi

Reputation: 281

Return true in JavaScript when call function from OnClientClick

When I use this code:

<asp:Button runat="server" ID="Block" Text="text"  OnClientClick="return BlockCheck()"   OnClick="BtnBlockClick"  CausesValidation="False"/>


function BlockCheck() {
            if (x) {
                document.getElementById('#ErrorText').text('Error');
                return false;
            }
        return true;
    }

but this for this part : document.getElementById('#ErrorText').text('Error');<br>to return true.

Upvotes: 0

Views: 548

Answers (1)

raina77ow
raina77ow

Reputation: 106443

First, you don't need # in getElementById's param: it really should be written like this...

document.getElementById('ErrorText')

With # that'll try to find an element with ID literally equal to '#ErrorText'- that'll fail, so the function will return null. And any attempt to work with null afterwards (calling some methods off it, in particular) will fail with an Error raised.

Second, you seem to mix jQuery functions and JavaScript ones: there's no text method in DOMElements. Strictly speaking, you'll have to check for textContent support, then go with it; if it's not supported, use innerText instead. For example:

var el = document.getElementById('ErrorText');
el['textContent' in el ? 'textContent' : 'innerText'] = 'Error';

Apparently the check's not required if your project doesn't have to support IE8-.

Upvotes: 2

Related Questions