简体   繁体   English

asp.net/javascript,为什么文本框的onChange事件不触发?

[英]asp.net/javascript, why is textbox onChange event does not fire?

I want it to happen when after user select the userID then the userID show up on first readonly textbox then the onChange event should fire when it show on first readonly textbox so it can copy this userID to second textbox. 我希望当用户选择userID之后,该userID出现在第一个只读文本框上,然后在第一个只读文本框上显示onChange事件时触发onChange事件,以便可以将此userID复制到第二个文本框。 However it doesn't work, it only worked is the userID show up on first textbox but the onChange doesn't trigger for second texbox. 但是,它不起作用,只有在第一个文本框上显示了userID时才起作用,但是onChange不会为第二个texbox触发。

Here half working codes: 这是一半的工作代码:

<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>

Then a javascript codes in <head> to copy first textbox value and put to second textbox: 然后<head>的javascript代码复制第一个文本框值并放入第二个文本框:

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

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

            </script>

Edited: I add a GALModalDialog.js codes here because some of you want to see what it like. 编辑:我在这里添加了GALModalDialog.js代码,因为有些人想看看它是什么样的。 I also have GALToCCDialong.asp that listed userid to choose and XMLGALListbox.asp that get the userid from ADs. 我也有GALToCCDialong.asp和XMLGALListbox.asp,其中列出了要选择的用户ID,XMLGALListbox.asp从广告中获取了用户ID。

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;
}

Edited: Here is codes of GALToCCDialog.asp. 编辑:这是GALToCCDialog.asp的代码。 In SubmitOnclick function and else if(vAction == 'OK') is where I click OK button from selected userid to submit to textbox. 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>

Use 采用

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

instead of 代替

document.getElementById('tbAdd_Sphone')

MSDN Control.ClientID Property MSDN Control.ClientID属性

You cannot make change event just by setting value from javascript. 您不能仅通过设置javascript的值来进行更改事件。 Here is a sample by using trigger. 这是使用触发器的示例。

 <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>

Here is your code, removing those validators 这是您的代码,删除了那些验证器

<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>

Server side. 服务器端。

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

Changing the value of tbAdd_Sowner through JavaScript (I assume through your GalModalTOCCDialog function) isn't going to fire the onchange event. 通过JavaScript(我想通过您的GalModalTOCCDialog函数)更改tbAdd_Sowner的值不会触发onchange事件。

You can fire that event manually, after you set the value: 设置值后,您可以手动触发该事件:

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

Though I'm surprised you aren't have problems with getElementById like @IrfanTahirKheli showed, which should've worked fine for you... so there are likely missing pieces of your markup that we need to help you correctly. 尽管让我感到惊讶的是, getElementById并没有像@IrfanTahirKheli所示的问题,它应该对您来说还不错……所以您可能缺少一些标记,我们需要正确地帮助您。

Other things you need to strongly consider is to not use inline styling and not use tables for formatting. 您需要强烈考虑的其他事项是不使用内联样式和不使用表格进行格式化。

Since you seem to have problems with what I added, here is another way. 由于您似乎对我添加的内容有疑问,因此这是另一种方法。 Remove the onChange from your asp:TextBox and just do it all from javascript: 从您的asp:TextBox删除onChange ,然后从javascript中全部删除:

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

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

Like others have mentioned in their answers, 就像其他人在回答中提到的那样,

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

will have a server-side dynamic client-ID prefixed to the generated HTML. 将在生成的HTML之前添加服务器端动态客户端ID。 If you see the source code of the page (or use the developer tools) in a browser of choice, you will notice you the ID is different than what you are passing in to your method call ie something like this: 如果您在选择的浏览器中看到页面的源代码(或使用开发人员工具),则会注意到ID与传递给方法调用的ID不同,即类似以下内容:

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

You can keep the className static by using class="tbAdd_Sphone" if the class is dynamically prefixed too. 如果类也是动态前缀,则可以通过使用class =“ tbAdd_Sphone”来使className保持静态。 Or, try to get element by ID on 或者,尝试通过ID获取元素

<%=tbAdd_Sphone.ClientID %>

You can either set the ClientID mode to static , or you can try using UniqueID. 您可以将ClientID模式设置为static ,也可以尝试使用UniqueID。

Another thing to note, javascript has a special behavior. 另外要注意的是,javascript具有特殊的行为。 If you call of a method with a set number of variables passed in correctly in the call, it will only use those values in the functionality. 如果您调用的方法在调用中正确传递了一定数量的变量,则它将仅在功能中使用这些值。 If there is null/undefined data passed into the call, the rest of the parameters are just ignored. 如果有空/未定义的数据传递给调用,则其余参数将被忽略。

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

If you need to use the id for phone, either do a substring search for getting the element by the actual ID, or use a getElementsByTag in your javascript to search for textboxes, and you can use any other property, say in plain Javascript: 如果您需要使用电话的ID,请执行子字符串搜索以通过实际ID获取元素,或者在JavaScript中使用getElementsByTag来搜索文本框,并且可以使用其他任何属性,例如以纯Javascript表示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在asp.net用户控件中无法正确触发文本框onchange事件? - Why doesn't textbox onchange event fire correctly within asp.net user control? 为什么在启用自动填充功能时,javascript onchange事件不会触发? - Why does the javascript onchange event not fire if autocomplete is on? javascript onchange事件到asp.net下拉列表 - javascript onchange event to asp.net dropdownlist ASP.NET MVC:下拉菜单和文本框onchange事件之间的区别 - asp.net mvc: difference between dropdown & textbox onchange event 当onkeyup事件定义“ setTimeout”(IE9)时,ASP.NET / Webform文本框不会触发自动回发 - ASP.NET/Webform Textbox does not fire the autopostback when onkeyup event defines “setTimeout” (IE9) 在输入按下时触发ASP.NET TextBox事件 - Fire an ASP.NET TextBox event on enter press 显示文本框onchange asp.net - Display textbox onchange asp.net 为什么我的文本框的onchange事件在模糊时触发-不是每个键入的字符都触发? - why onchange event of my textbox fires on blur - does not fire by every typed character? 如何从ASP.NET中的JavaScript触发按钮单击事件 - How to fire a button click event from JavaScript in ASP.NET 触发事件以在ASP.NET中获取JavaScript值 - Fire event to get javascript value in asp.net
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM