簡體   English   中英

javascript在HTML按鈕上清除asp文本框,然后單擊

[英]javascript clear asp textbox on html button click

單擊按鈕(html)時,我想清除一個asp文本框。

所以基本上JS函數是:

<script type="text/javascript">
    function clearTextBox() {
        document.getElementByID('<%=txtFName.ClientID%>').value = "";
    }
</script>

和一個asp.net TextBox

<asp:TextBox ID="txtFName" runat="server" class="form-control" placeholder="First name" AutoCompleteType="Disabled" MaxLength="30" />

還有一個HTML按鈕

<span class="input-group-btn">
<button class="btn default" id="clearButton" type="button" onclick="clearTextBox()"><i class="fa fa-times"></i></button>
</span>

所有按鈕和其他控件都位於asp更新面板中(不知道是否有所不同)

單擊HTML clearButton時沒有任何反應,Web控制台上的錯誤:

Uncaught TypeError: undefined is not a function
clearTextBox 
onclick

我建議將JS添加到Head part of page. 那么它將不會創建Uncaught ReferenceError: clearTextBox is not defined

嘗試傳遞文本框的ID,在您的情況下應為:

document.getElementByID('txtFName').value = "";

然后分配方法給你輸入這樣的東西

asp:textbox ..... onClick="yourMethodName"

將您以下的js代碼移至頁面標題或其他位置,目前無法找到您的js函數。 由於某些錯誤或中斷,它必定會中斷。 或者嘗試將js alert / debugger放入您的js函數中,以確保您甚至可以找到此函數。 清除文本框是下一步。

<script type="text/javascript">
function clearTextBox() {
    alert('Hello World');
}</script>

現在,如果您能夠看到警報,那么您的代碼就可以找到您的函數。 然后像這樣修改您的文本框標記:

<asp:TextBox CliendIDMode="Static" ID="txtFName" runat="server" class="form-control" placeholder="First name" AutoCompleteType="Disabled" MaxLength="30" />

現在,修改您的clearTextBox函數,如下所示:

<script type="text/javascript">
function clearTextBox() {
    document.getElementById('txtFName').value = '';
}</script>

您需要添加

ClientIDMode="Static"

這樣您的文本框將如下所示

<asp:TextBox CliendIDMode="Static" ID="txtFName" runat="server" class="form-control" placeholder="First name" AutoCompleteType="Disabled" MaxLength="30" />

在asp.net中,當頁面呈現控件ID更改時

我建議你應該使用jQuery。

$("#txtFName").val("");

在您的javascript函數中還返回false

也可以嘗試將您的JS塊

function clearTextBox() {
   var elements = [] ;
    elements = document.getElementsByClassName("form-control"); // your class name 

    for(var i=0; i<elements.length ; i++){
       elements[i].value = "" ;
    }
}

更改

document.getElementByID

document.getElementById

而且有效。 歸功於Mudassar

謝謝大家!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM