【问题标题】:asp.net/javascript, why is textbox onChange event does not fire?asp.net/javascript,为什么文本框 onChange 事件不触发?
【发布时间】:2013-09-23 18:17:50
【问题描述】:

我希望在用户选择用户 ID 之后发生这种情况,然后用户 ID 显示在第一个只读文本框中,然后 onChange 事件应该在它显示在第一个只读文本框上时触发,以便它可以将此用户 ID 复制到第二个文本框。但是它不起作用,它只起作用是用户ID显示在第一个文本框上,但 onChange 不会触发第二个文本框。

这里有一半的工作代码:

<tr>
    <td align="right">
        Secondary Owner
    </td>
    <td>
        <input id="Hidden1" type="hidden" />
        <asp:TextBox ID="tbAdd_Sowner" runat="server" Enabled="false"></asp:TextBox>
        <input id="Hidden2" type="hidden" />
        <input id="Hidden3" type="hidden" />
        <a href="javascript:void(0)" onclick="GalModalTOCCDialog(Hidden1, tbAdd_Sowner, Hidden2,Hidden3)">
            Get User ID</a>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator7" ValidationGroup="g1" runat="server" ErrorMessage="* Required" ControlToValidate="tbAdd_Sowner"> <b style="color:Red;"> * </b></asp:RequiredFieldValidator>
        <asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender8" runat="server" TargetControlID="RequiredFieldValidator7">
        </asp:ValidatorCalloutExtender>
    </td>
</tr>
<tr>
    <td align="right">Secondary Owners</td>
    <td>
        <asp:TextBox ID="tbAdd_Sphone" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator13" ValidationGroup="g1" runat="server" ErrorMessage="* Required" ControlToValidate="tbAdd_Sphone"> <b style="color:Red;"> * </b></asp:RequiredFieldValidator>
        <asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender9" runat="server" TargetControlID="RequiredFieldValidator13">
        </asp:ValidatorCalloutExtender>
    </td>
</tr>

然后&lt;head&gt; 中的 javascript 代码复制第一个文本框值并放入第二个文本框:

 <script>
        function getUserID() {
            document.getElementById('tbAdd_Sphone').value = document.getElementById('tbAdd_Sowner').value;
        }

document.getElementById('tbAdd_Sowner').onchange = getUserID();

            </script>

已编辑:我在这里添加了一个 GALModalDialog.js 代码,因为你们中的一些人想看看它喜欢什么。我还有列出要选择的用户 ID 的 GALToCCDialong.asp 和从 AD 获取用户 ID 的 XMLGALListbox.asp。

function PopulateListboxFromString(oListbox,vNames,vUserIDs){

    var oArrayUserNames = vNames.value.split(';');
    var oArrayUserIDs = vUserIDs.value.split(';');

    for (var index=0;index < oArrayUserIDs.length;index++) {

        if (oArrayUserNames[index] != ''){
            var oOption = document.createElement("OPTION");
            oListbox.options.add(oOption);
            oOption.innerText = oArrayUserNames[index];
            oOption.value = oArrayUserIDs[index];
        }
    }   
};

function GalModalTOCCDialog(oTONames, oTOUserIDs,oCCNames, oCCUserIDs ) {


        if (oCCNames != null){

            var oInputArray = new Array(oTONames.value,oTOUserIDs.value,oCCNames.value,oCCUserIDs.value);

        } else {

            var oInputArray = new Array(oTONames.value,oTOUserIDs.value,'','');

        }

        var oOutputArray = window.showModalDialog('GalAccess/GALToCCDialog.asp', oInputArray, 'dialogWidth:510px;dialogHeight:400px;status:no;help:no;');





        // Check if we get something back; 
        // User might have closed the window without using the buttons
        if (oOutputArray != null){

            //first element is true if user clicked OK

            if (oOutputArray[0]) {

                if (oCCNames != null){

                    oTONames.value = oOutputArray[1];
                    oTOUserIDs.value = oOutputArray[2];
                    oCCNames.value = oOutputArray[3];
                    oCCUserIDs.value = oOutputArray[4];

                } else {

                    oTONames.value = oOutputArray[1];
                    oTOUserIDs.value = oOutputArray[2];     
                }



            } 
        }

    return false;
}

function GalModalDialog(oSelectObject, oUserID) {

    if (oUserID == null){
        // there is a select object to fill data from
        // fill the input array
        var oInputArray = new Array(new Array(oSelectObject.options.length),new Array(oSelectObject.options.length));

        for (var index=0;index < oInputArray[0].length;index++) {
            oInputArray[0][index] = oSelectObject.options[index].innerText;
            oInputArray[1][index] = oSelectObject.options[index].value;

        };

        var oOutputArray = window.showModalDialog('../GALDialog/GALModalDialog.asp', oInputArray, 'dialogWidth:500px;dialogHeight:320px;status:no;help:no;');

        // Check if we get something back; 
        // User might have closed the window without using the buttons
        if (oOutputArray != null){

            //first element is true if user clicked OK

            if (oOutputArray[0]) {
                //remove existing from end to beginning otherwise not all options are removed.

                var length=oSelectObject.options.length;
                for (var index=length-1;index >= 0;index--) {
                    oSelectObject.options[index] = null;
                };

                // copy the array   
                for (var index=0;index < oOutputArray[1].length;index++) {
                    var oOption = document.createElement("OPTION");
                    oSelectObject.options.add(oOption);
                    oOption.innerText = oOutputArray[1][index];
                    oOption.value = oOutputArray[2][index];

                };
            } 
        }
    } else
    {
        // there are 2 text objects to fill data from; the first contains the name, the secound the userid.
        //if (oSelectObject.value != '' ) {
        //  var oInputArray = new Array(new Array(1),new Array(1));
        //
        //  oInputArray[0][0] = oSelectObject.value;
        //  oInputArray[1][0] = oUserID.value;

        //} else {

                var oInputArray = new Array(new Array(0),new Array(0));

        //}     
        var oOutputArray = window.showModalDialog('../GALDialog/GALModalDialog.asp', oInputArray, 'dialogWidth:500px;dialogHeight:320px;status:no;help:no;');

        if (oOutputArray != null){

            //first element is true if user clicked OK

            if (oOutputArray[0]) {

                // copy the data    
                oSelectObject.value = oOutputArray[1][0];
                oUserID.value = oOutputArray[2][0];


            } 
        }
    }
    return false;
}

已编辑: 这里是 GALToCCDialog.asp 的代码。在SubmitOnclick 函数和else if(vAction == 'OK') 中,我从选定的用户ID 中单击“确定”按钮以提交到文本框。

<SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript>
<!--

function List_onkeydown(oList) {

    if( event.keyCode == 46 ){

        if ((oList.selectedIndex != -1)&&(oList.options[oList.selectedIndex].value != '')){
            oList.options[oList.selectedIndex] = null;

        }
    }
}

//-->
</SCRIPT>


<script language="jscript">



function InitializeListbox(idXML, idSpan){

    // get to the XML specifying the names
    var oSelects;
    var strXML;

    oSelects  = idXML.XMLDocument.documentElement.childNodes;
    strXML = '';
    // Get all the options in 1 string
    for (var index=0;index< oSelects.length;index++){
        strXML = strXML + oSelects[index].xml;
    }
    // the error handlingis there if idSpan refers to multiple objects

    // Insert the options in the html before the end of the SELECT
    // window.alert(strXML);
    //idSpan.innerHTML = replace(idSpan.innerHTML,"</SELECT>",strXML & "</SELECT>");
    idSpan.innerHTML = '<SELECT id=idUserSelect size=12 style="width:190px">' + strXML + '</SELECT>';
}

function SubmitOnclick(vAction, oObject){

    //DistList.action = "DistList.asp?Action=" & vAction ;

    if (vAction == 'Add'){

        if ((idUserSelect.value!='')&&(idUserSelect.value!='Unknown')){
            var oOption = document.createElement("OPTION");
            oObject.options.add(oOption);
            oOption.innerText = idUserSelect.options[idUserSelect.selectedIndex].text;
            oOption.value = idUserSelect.options[idUserSelect.selectedIndex].value;
        }
    }   else if(vAction == 'Find') {
        idXMLUsers.src ='XMLGALListbox.asp?Searchstring=' + SearchString.value;

    } else if(vAction == 'Remove'){

        if ((idMyList.selectedIndex != -1)&&(idMyList.options[idMyList.selectedIndex].value != '')){
            idMyList.options[idMyList.selectedIndex] = null;
        }
    } else if(vAction == 'OK'){

        //window.returnValue = cal.day + ' ' + MonthNames[cal.month-1] + ' ' + cal.year ;
        // create an array

        var TONames = ''
        var TOUserIDs = ''
        var CCNames = ''
        var CCUserIDs = ''

        for (var index = 0; index < 1; index++) {
            TONames = TONames + idTOList.options[index].innerText;
            TOUserIDs = TOUserIDs + idTOList.options[index].value;
        };

        //Commented out by Nick, use if you want multiple userIDs etc...
        //for (var index=0;index < idTOList.options.length;index++) {
        //  TONames = TONames + idTOList.options[index].innerText  ;
        //  TOUserIDs = TOUserIDs + idTOList.options[index].value ;         
        //};

        //for (var index=0;index < idCCList.options.length;index++) {
            //CCNames = CCNames + idCCList.options[index].innerText ;
            //CCUserIDs = CCUserIDs + idCCList.options[index].value ;

        //};

        var oArray = new Array(true,TONames,TOUserIDs,CCNames,CCUserIDs);

        window.returnValue = oArray;

        //window.alert(TONames);
        //window.alert(TOUserIDs);
        //window.alert(CCNames);
        //window.alert(CCUserIDs);

        window.close();

    } else if(vAction == 'Cancel'){
        var oArray = new Array(false);
        window.returnValue = oArray;
        window.close();

    }   

}

function OnBodyLoad() {

    //window.alert('test');
    //clear all list data

    try{
        var oArray = window.dialogArguments;

        //PopulateListboxFromString(idTOList,oArray[0],oArray[1])
        //PopulateListboxFromString(idCCList,oArray[2],oArray[3])

    } catch(e)
    {
    }

};

function PopulateListboxFromString(oListbox,vNames,vUserIDs){

    var oArrayUserNames = vNames.split(';');
    var oArrayUserIDs = vUserIDs.split(';');
    for (var index=0;index < oArrayUserIDs.length;index++) {

        if (oArrayUserNames[index] != ''){
            var oOption = document.createElement("OPTION");
            oListbox.options.add(oOption);
            oOption.innerText = oArrayUserNames[index];
            oOption.value = oArrayUserIDs[index];
        }
    }   

};

function OnBodyLoad__() {

    //window.alert('test');
    try{
        var oArray = window.dialogArguments;

        for (var index=0;index < oArray[0].length;index++) {
            var oOption = document.createElement("OPTION");
            idMyList.options.add(oOption);
            oOption.innerText = oArray[0][index];
            oOption.value = oArray[1][index];

        };
    } catch(e)
    {

    };
};

</script>
<body class="cellcolorlightest content" onload="OnBodyLoad();">
<xml id="idXMLUsers" src="XMLGALListbox.asp?Searchstring=" ondatasetcomplete="InitializeListbox(idXMLUsers, idUsers);"></xml>

    <table class="TableBorderNormal" width="100%" border=0 cellspacing="1" cellpadding="1">
    <colgroup>
        <col width="50%"></col><col></col><col width="50%"></col>
        <thead>

        <tr>
         <td colspan="3" class="TDvwvInfo" align="left"><STRONG>Find Name</STRONG><br><FONT size=2>Type name and hit "Search"</FONT></td>
        </tr>

        <tr>
         <td  class="TDvwvInfo" align="left"><input name="SearchString" style="WIDTH: 190px" size="20"> &nbsp;</td>
         <td class="TDvwvInfo" align="middle" valign=top><input  type="button" value="Search" name="Find" onclick="SubmitOnclick('Find')"></td>
         <td class="TDvwvInfo" align="left"></td>
        </tr>

        <tr>
         <td class="TDvwvInfo" align="left" nowrap><STRONG>Users found</STRONG><br><FONT size=2>Select from list and hit "Select" to add</FONT></td>
         <td class="TDvwvInfo" align="middle"></td>
         <td class="TDvwvInfo" align="left" valign=top><STRONG>Get User ID</STRONG><br></td>
        </tr>

        </thead>

        <tr>
         <td class="TDvwv" align="left" width="33%" rowspan=2  valign=top><span id="idUsers">   </span> </td>               
         <td class="TDvwvInfo" align="middle" valign=top width="33%">
         <input  type="button" value="Select &gt;" name="Add" onclick="SubmitOnclick('Add', idTOList);"><br><br>&nbsp;
         </td>
         <td class="TDvwv" align="left" width="33%"  valign=top>
          <select id="idTOList" size="5" style="WIDTH: 190px" LANGUAGE=javascript onkeydown="return List_onkeydown(this)"> </select><br>&nbsp;
          <br />
          <b style="color:red">* Only add one user, if you added the wrong user click cancel and try again.</b>
          </td>
        </tr>

            <tr>
                 <td align=middle  valign=top>
                 <!-- <input type="hidden" value="CC  >" name="CC" onclick="SubmitOnclick('Add', idCCList);" disabled="disabled"><br><br>&nbsp;--> <!--INPUT name=Remove onclick="SubmitOnclick('Remove');" type=button value="  < Remove"--></td>
                 <td align=left  valign=top>
                  <!--<select id=idCCList size=5 style="WIDTH: 190px" LANGUAGE=javascript onkeydown="return List_onkeydown(this)" disabled="disabled" visible="false"></select></td>-->

            </tr>

        <tr>
         <td align="middle" ></td>
         <td align=middle></td>
         <td align=left>
          <input type="button" value="OK" name="OK" onclick="SubmitOnclick('OK',null);">&nbsp;&nbsp;
          <input type="button" value="Cancel" name="Cancel" onclick="SubmitOnclick('Cancel',null);"></td>
        </tr>
    </table>

</body>
</html>

【问题讨论】:

  • 您需要使用我认为的服务器控件的 ClientID。并且您正在尝试在函数之外添加EventListener。
  • 用户ID在选择后已经插入到tbAdd_Sowner。 onChange 应该在插入时触发。
  • 你试图在函数外添加EventListener ..这不是问题吗?

标签: javascript html asp.net


【解决方案1】:

使用

document.getElementById('<%= tbAdd_Sphone.ClientID %>')

而不是

document.getElementById('tbAdd_Sphone')

MSDN Control.ClientID Property

【讨论】:

  • 我收到了错误,异常详细信息:System.Web.HttpException:无法修改控件集合,因为控件包含代码块(即 )。源错误:在执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常起源和位置的信息。
  • 这是因为 Gridview 正在生成 id 运行时。所以可以通过遍历gridview行来做到这一点
  • 对不起,我不明白。我已经在 tbAdd_Sowner 中插入了 userId。选择后,它会自动粘贴到此文本框,然后它应该触发复制它。
  • 我检查警报。它表明 onChange 不会触发,因为警报弹出窗口永远不会出现。
  • 您是手动将文本放在第一个文本框中还是针对某个事件分配它?
【解决方案2】:

通过 JavaScript 更改 tbAdd_Sowner 的值(我假设通过您的 GalModalTOCCDialog 函数)不会触发 onchange 事件。

您可以在设置值后手动触发该事件:

document.getElementById('tbAdd_Sowner').onchange();

虽然我很惊讶你没有像@IrfanTahirKheli 展示的那样对getElementById 有问题,这对你来说应该没问题...所以可能缺少你的标记部分,我们需要正确地帮助你.

您需要认真考虑的其他事项是不要使用内联样式,也不要使用表格进行格式化。

由于您似乎对我添加的内容有疑问,这里有另一种方法。从asp:TextBox 中删除onChange,然后从javascript 中完成所有操作:

 document.getElementById('tbAdd_Sowner').value = 'somevalue';
 document.getElementById('tbAdd_Sowner').onchange = getUserID();

【讨论】:

  • 'tbAdd_Sowner' id 在渲染后没有改变,因为 OP 没有使用任何容器。您可以在此处找到详细信息 - MSDN- 在 AutiID 的描述中。我会说使用客户端 ID 可能会在很多地方拯救我们,但可能不会在这里。
  • @afzalulh 很可能,是的,渲染时 ID 已更改。它是否在容器中并不重要。它是一个服务器控件。
  • 请检查链接。或者使用页面中的服务器控件(没有母版页)测试自己,然后查看呈现的 ID。
  • @afzalulh 好的,如果他不使用母版页,你是对的。但是由于 ClientID 对他不起作用,你注意到我把它从我的答案中排除了;)
  • +1 @MikeSmithDev - 对于 OP,我会有相同的答案。关于 ID,我测试了他将 tr 放在表格中的代码,它给了我正确的 id:我为什么要打扰母版页,而他没有提到 :-)
【解决方案3】:

您不能仅通过从 javascript 设置值来进行更改事件。这是一个使用触发器的示例。

 <script>
       $(document).ready(function () {

           $(".tbAdd_Sowner").on('change', function () {
               var owner = $('.tbAdd_Sowner').val();
               $('.tbAdd_Sphone').val(owner);
           });

           $(".aGetID").on('click', function () {
               var tbOwner = $('.tbAdd_Sowner');
               var hidden1 = $('.Hidden1');
               var hidden2 = $('.Hidden2');
               var hidden3 = $('.Hidden3');
               GalModalTOCCDialog(hidden1, tbOwner, hidden2, hidden3);

           });

           function GalModalTOCCDialog(Hidden1, tbAdd_Sowner, Hidden2, Hidden3) {
               $(tbAdd_Sowner).val(' ').trigger('change');
           }

           $('.tbAdd_Sowner').change(function () {
               $(this).removeAttr('disabled');

           });
       });
    </script>

这是你的代码,删除那些验证器

<table>
        <tr>
            <td align="right">Secondary Owner
            </td>
            <td>
                <input id="Hidden1" type="hidden" value="1" class="Hidden1"  />
                <asp:TextBox ID="tbAdd_Sowner" OnTextChanged="tbAdd_Sowner_TextChanged" CssClass="tbAdd_Sowner" AutoPostBack="true" runat="server" Enabled="false"   ></asp:TextBox>
                <input id="Hidden2" type="hidden" class="Hidden2" />
                <input id="Hidden3" type="hidden" class="Hidden3" />
                <a href="javascript:void(0)" id="aGetID" class="aGetID" >Get User ID</a>

            </td>
        </tr>
        <tr>
            <td align="right">Secondary Owners</td>
            <td>
                <asp:TextBox ID="tbAdd_Sphone" runat="server" CssClass="tbAdd_Sphone" ></asp:TextBox>

            </td>
        </tr>
    </table>

服务器端。

protected void tbAdd_Sowner_TextChanged(object sender, EventArgs e)
        {
            tbAdd_Sowner.Text = "123";
        }

【讨论】:

  • 我没有看到 GalModalTOCCDialog 脚本文件。即负责获取AD名称、uid等。
  • 查看 Jquery #aGetID 点击事件。您也可以使用 $('#tbAdd_Sowner').val() 获取 textobx 值
  • 好吧,我没有删除&lt;a href="javascript:void(0)" onclick="GalModalTOCCDialog(ToName2, tbAdd_Powner, CCName2,CCUserID2)"&gt;。但是我加了&lt;a href="javascript:void(0)" id="aGetID" &gt;Get User Name&lt;/a&gt; 还是不行Get User ID
  • @StudentIT:好的,您现在可以查看 Jquery。我把你的函数加回来了。
  • 您不能假设“tbAdd_Sowner”保持不变,因为它是一个服务器控件。根据您的设置,ID 更改很可能类似于“ctl14_tbAdd_Sowner”。
【解决方案4】:

使用这个<asp:TextBox ID="TextBox1" runat="server" onkeypress="document.getElementById('id').Value=this.value;" />

【讨论】:

    【解决方案5】:

    就像其他人在回答中提到的那样,

      <asp:TextBox id="tbAdd_Sphone" runat="server" />
    

    将在生成的 HTML 前添加一个服务器端动态客户端 ID。如果您在选择的浏览器中看到页面的源代码(或使用开发人员工具),您会注意到您的 ID 与您传递给方法调用的 ID 不同,例如:

    <textarea id="ctl00_OuterASPControlID_tbADD_Sphone"></textarea>
    

    如果类也是动态前缀,您可以使用 class="tbAdd_Sphone" 使类名保持静态。或者,尝试通过

    上的 ID 获取元素
    <%=tbAdd_Sphone.ClientID %>
    

    You can either set the ClientID mode to static,或者您可以尝试使用 UniqueID。

    另外需要注意的是,javascript 有一个特殊的行为。如果您调用具有在调用中正确传入的一组变量的方法,它将仅在功能中使用这些值。如果有 null/undefined 数据传递到调用中,则其余参数将被忽略。

    functionName:function(parameter1, parameter2) { 
    
                //Default behavior can be overridden if parameter2 is not passed in as expected.
                if(parameter2 ==null || parameter2=='undefined') { 
                    parameter2 = "Some value"; 
                        } 
    }
    
    
        functionName("testPar1");               //Works but parameter2 is not passed in as expected
        functionName("testPar1", "testPar2");   //Works
        functionName("testPar1", undefined);    //Works, but parameter2 is not passed in as expected
    

    如果您需要为电话使用 id,请执行子字符串搜索以通过实际 ID 获取元素,或者在您的 javascript 中使用 getElementsByTag 来搜索文本框,您可以使用任何其他属性,简单地说Javascript:

    var x = document.getElementsByTag("textbox"); 
    if(x!=null && x.attribute('class') == 'tbAdd_Sphone' )  { 
     var valueX = x.attribute('value'); 
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      相关资源
      最近更新 更多