Javascript – Pass an ASP.Net control into JavaScript function

asp.netcontrolsjavascript

I've written a javascript function which I want to take in a textbox, dropdownlist and a integer. Within the function I need to check the length of the text string and the value of the DDL. The function is below:

function CheckSearch(name, code, iMinSize) {
if (name.value.length < iMinSize && code.value === '') {
    alert('You must enter ' + iMinSize + ' letters or more when searching.');
    name.focus();
    return false;
}
else {
    return true;
}

}

I think the function is OK but I can't seem to call it from a Button control in ASP.NET.

Here is my button tag:

<asp:Button ID="buttonSearch" runat="server" Text="Search" OnClick="buttonSearch_Click"
                OnClientClick="javascript:return CheckSearch('textBoxSearch','comboCodes', 3);" />

When I click the button I receive an Object Expected error.

The code break on the following line:

<input type="submit" name="ctl00$contentBody$buttonSearch" value="Search" onclick="return CheckSearch(document.getElementById(&#39;textBoxSearch&#39;),document.getElementById(&#39;comboCodes&#39;), 3);" id="contentBody_buttonSearch" /> 

The error message is: Microsoft JScript runtime error: Object expected

Please help.

I'm using ASP.NET4.0

Thanks

Best Solution

At the bottom of your page, I would add references to your various client IDs. For example:

<script type="text/javascript">
  var buttonSearch  = document.getElementById('<%= buttonSearch.ClientID %>');
  var textBoxSearch = document.getElementById('<%= textBoxSearch.ClientID %>');
  var comboCodes    = document.getElementById('<%= comboCodes.ClientID %>');
</script>

You could then refer to those DOM objects in your client click:

<asp:Button ID="buttonSearch" runat="server" Text="Search" OnClick="buttonSearch_Click"
                OnClientClick="return CheckSearch(textBoxSearch, comboCodes, 3);" />

Now your handler doesn't have to change, since you passed in the correct DOM objects:

if (name.value.length < iMinSize && code.value === '') {
    alert('You must enter ' + iMinSize + ' letters or more when searching.');
    name.focus();
    return false;
}

Another way you could do it is to set the ClientIDMode to static on each control:

<asp:TextBox ID="textBoxSearch" runat="server" ClientIDMode="Static" />

Now, you can access the value of this text box with:

document.getElementById('textBoxSearch').value;