简体   繁体   中英

enable asp.net button using javascript

I have this application where I want to enable asp.net button using javascript. JavaScript code:

function Enable() {
  document.getElementById('<%= Begin.ClientID %>').disabled = false;
}

Asp button:

<asp:Button ID="Begin" runat="server" Text="Submit" OnClick="Button1_Click"/>

I am using ClientScriptBlock to call Enable function:

protected void Page_Load(object sender, EventArgs e)
{
  Begin.Enabled = false;
  ClientScript.RegisterClientScriptBlock(GetType(), "EnableButton", "Enable();", true);
}

However when I run application I get an error:

0x800a138f - Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object

Can anyone help me with that?

I want this to check, if user has activated JavaScript on the browser. If JavaScript is not enabled, the button remains disabled.

It appears that the javascript code is placed in a separate javascript file. But you seem to have used some <% %> server side tags in it which obviously will not be processed. Those tags work only inside your ASPX pages. So I guess that inside your ASPX page you need to declare a variable:

<script type="text/javascript">
    var beginClientId = '<%= Begin.ClientID %>';
</script>

and then inside your separate .js file you could use it:

function Enable() {
  document.getElementById(beginClientId).disabled = false;
}

Or if you are using ASP.NET 4.0 just turn static or predicatble ids :

<system.web>
    <pages clientIDMode="Static"></pages>
    <compilation debug="true" targetFramework="4.0" />
</system.web>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM