如何通过 JavaScript 发送 asp.net 控件的客户端 ID

How to send clientid of asp.net control via JavaScript

本文关键字:控件 客户端 ID net asp 何通过 JavaScript 发送      更新时间:2023-09-26

我正在尝试在以下 asp.net 代码中单击按钮时发送控件 ID:

  <asp:TextBox ID="empid" runat="server" CssClass="input_box" onFocus="if (this.value == this.title) this.value='';" onBlur="if (this.value == '')this.value = this.title;" value="Enter employee ID" title="Enter employee ID" onClick="changecol(this)"></asp:TextBox>
 <asp:Button ID="abc" runat="server" Text="xxx" 
        CssClass="submit_button" onclick="abc_Click" OnClientClick="return checkEmpid('<%=empid.ClientID%>')"/>

而Javascript是:

function checkEmpid(id){
var idValue = document.getElementById(id).value;
alert(idValue);
return false;
}

在警报中,当我使用以下代码时,我得到空:

<asp:TextBox ID="empid" runat="server" CssClass="input_box" onFocus="if (this.value == this.title) this.value='';" onBlur="if (this.value == '')this.value = this.title;" value="Enter employee ID" title="Enter employee ID" onClick="changecol(this)"></asp:TextBox>
 <asp:Button ID="abc" runat="server" Text="xxx" 
        CssClass="submit_button" onclick="abc_Click" OnClientClick="return checkEmpid()"/>
function checkEmpid(){
var idValue = document.getElementById('<%=empid.ClientID%>').value;
alert(idValue);
return false;
}

在警报中,我在文本框中输入了值。请帮助我解决这个问题,我想将控件的客户端 id 作为 JS 的参数发送。

如果您肯定想通过参数传递 UserControl 名称,我相信您唯一的选择是在代码隐藏中设置函数调用......

C#...

abc.OnClientClick = string.Format("return checkEmpid('{0}');", empid.ClientID);

VB.NET...

abc.OnClientClick = String.Format("return checkEmpid('{0}');", empid.ClientID)

(已更新,因为我意识到您想要文本框 ID,而不是用户控件 ID)

你可以通过这种方式将empid文本框的客户端ID发送到javascript。

    abc.Attributes.Add("onclick", "return checkEmpid('" + empid.ClientID + "')");

    function checkEmpid(clientIdOfempid){      
        alert("This is id of TextField with ID=empid >> "+clientIdOfempid);
        return false;
    }

您可以通过'<%=empid.ClientID%>'这种方式获取客户端 ID

function checkEmpid(){
    var id = '<%=empid.ClientID%>';
    alert("This is id of TextField with ID=empid >> "+id);
    return false;
}
alert('<%=empid.ClientID%>');

试试这个来获取ID

提醒 ID 不是更简单吗?

alert('<%=empid.ClientID%>');