使用 javascript 启用/禁用 ASP.NET 控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14343771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enable/Disable ASP.NET control with javascript
提问by Yiyi Chen
I'm building a page to upload an Excel file on the server for an import operation. So a found a javascript to check the file selected file extension void other file types. Now I'm trying to enable the upload ASP.NET button but javascript returns the error document.getElementById(...)is null.
我正在构建一个页面以在服务器上上传 Excel 文件以进行导入操作。所以找到了一个javascript来检查文件选择的文件扩展名无效其他文件类型。现在我正在尝试启用上传 ASP.NET 按钮,但 javascript 返回错误document.getElementById(...)为空。
Here the code:
这里的代码:
<script type="text/javascript" language="javascript" defer="defer">
function enableControl() {
document.getElementById('button').disable = false;
}
function disableControl() {
document.getElementById('button').disable = true;
}
function checkExcelFileUpload(elem) {
var filePath = elem.value;
if (filePath.indexOf('.') == -1)
return false;
var validExtensions = new Array();
var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
//Add valid extentions in this array
validExtensions[0] = 'xls';
//validExtensions[1] = 'pdf';
for (var i = 0; i < validExtensions.length; i++) {
if (ext == validExtensions[i])
return true;
}
elem.value = '';
alert('Sono ammessi solo file di Excel 97-2003');
return false;
}
</script>
<asp:FileUpload ID="fileupload" runat="server" size="50" onchange="javascript:try{if(checkExcelFileUpload(this) == true){enableControl();}else{disableControl();}}catch(err){alert(err);};" />
<asp:Button ID="button" runat="server" Text="Upload" Enabled="False" />
I serached on internet and I found other syntax for getElementByIdbut I still have this problem.
Can you help me?
我在互联网上搜索并找到了其他语法,getElementById但我仍然有这个问题。你能帮助我吗?
Thank you
谢谢
回答by Babak Naffas
Option 1Since your button is a server side control, the rendered ID will be different that what you have specified. Use the following code to generate the ctl$body$button(something along these lines depending on the nesting of your controls).
选项 1由于您的按钮是服务器端控件,因此呈现的 ID 将与您指定的不同。使用下面的代码来生成ctl$body$button(沿着这些线的东西,取决于你的控件的嵌套)。
document.getElementById('<%= button.ClientID %>')
Option 2If you are using ASP.NET 4, you can use the Staticclient ID mode.
选项 2如果您使用的是 ASP.NET 4,则可以使用Static客户端 ID 模式。
<asp:Button ID="button" runat="server" ClientIDMode="Static" Text="Upload" Enabled="False" />
<asp:Button ID="button" runat="server" ClientIDMode="Static" Text="Upload" Enabled="False" />
回答by psantiago
Instead of:
代替:
document.getElementById('button').disable = false;
You'll probably want:
你可能想要:
document.getElementById('<%= this.button.ClientID %>').disabled = false;

