Click here to Skip to main content
14,927,843 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello
I have an c# asp.net webform which uses a master page. I have coded a simple example to prove that I can use javascript to check for changes made to an AjaxControlToolkit ComboBox1. The example works perfectly and each time I select a new drop down item the selected item display in the textbox. Because it uses a master page the javascript has to reference the ComboBox1 as 'MainContent_ComboBox1' and the TextBox1 as '#MainContent_TextBox1'.

Now I need to make this work without a master page. I modified the default.aspx to remove MasterPageFile="~/Site.Master" and remove the "<asp:Content.." and added in and <scriptmanager> and changed the javascript from 'MainContent_ComboBox1 to ComboBox1 and #MainContent_TextBox1 to #TextBox1 but the Javascript is returning Null for $find('ComboBox1_ComboBox1').add_propertyChanged(function (sender, event) {

I have tried ComboBox1, ComboBox1_ComboBox1, 'ComboBox1', 'ComboBox1_ComboBox1', "ComboBox1", "ComboBox1_ComboBox1" and other variations without success. I don't understand why I am unable to reference ComboBox1 when there is no master page. Any advice would be welcome !!!

regards
Pat

Original default.aspx with Master Page (Working correctly)
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication13._Default" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="javascript2.js"></script>
       <div class="jumbotron">
       <h1>Test ComboBox</h1>
       <p>
            <cc1:ComboBox ID="ComboBox1" runat="server" AutoPostBack="false" OnSelectedIndexChanged="ComboBox1_SelectedIndexChanged">
            </cc1:ComboBox>
            <asp:TextBox ID="TextBox1" runat="server" BackColor="#CCFFCC" Width="530px" Height="21px">Please select a value from the dropdown box</asp:TextBox>
            <cc1:ComboBox ID="ComboBox2" runat="server" AutoPostBack="false" DropDownStyle="DropDownList" OnSelectedIndexChanged="ComboBox1_SelectedIndexChanged">
            </cc1:ComboBox>
            <p>
                <asp:Button ID="Button1" runat="server" Text="Next"  Width="188px" OnClick="Button1_Click" ForeColor="Green"/>
            </p>
                <p>
                <asp:Button ID="Button2" runat="server" Text="Button 2"  Width="188px" OnClick="Button2_Click"/>
            </p>
  </asp:Content>


Original java script (external javascript .js file) with Master Page (Working correctly)
$(document).ready(function () {
    $find('MainContent_ComboBox1').add_propertyChanged(function (sender, event) {
        console.log(event);
        console.log(sender);
        if (event.get_propertyName() == 'selectedIndex') {
            var newValue = sender.get_textBoxControl().value;
            $('#MainContent_TextBox1').val("You entered: " + newValue);
        }
    });
});


Modified default.aspx WITHOUT Master Page (Not Working )
<%@ Page Title="Home Page" Language="C#"  AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication20._Default" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<head runat="server">
 <title="xxx"></title>

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="javascript2.js"></script>
    </head>

    <form id="form1" runat="server" >
     <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
       <h1>Test ComboBox</h1>

       <p>
            <cc1:ComboBox ID="ComboBox1" runat="server" AutoPostBack="false" OnSelectedIndexChanged="ComboBox1_SelectedIndexChanged">
            </cc1:ComboBox>
            <asp:TextBox ID="TextBox1" runat="server" BackColor="#CCFFCC" Width="530px" Height="21px">Please select a value from the dropdown box</asp:TextBox>
            <cc1:ComboBox ID="ComboBox2" runat="server" AutoPostBack="false" DropDownStyle="DropDownList" OnSelectedIndexChanged="ComboBox1_SelectedIndexChanged">
            </cc1:ComboBox>
            <p>
                <asp:Button ID="Button1" runat="server" Text="Next"  Width="188px" OnClick="Button1_Click" ForeColor="Green"/>
            </p>
                <p>
                <asp:Button ID="Button2" runat="server" Text="Button 2"  Width="188px" OnClick="Button2_Click"/>
            </p>
        </form>


Modified javascript WITHOUT Master Page (Not Working )
$(document).ready(function () {
    $find('ComboBox1_ComboBox1').add_propertyChanged(function (sender, event) {
        console.log(event);
        console.log(sender);
        if (event.get_propertyName() == 'selectedIndex') {
            var newValue = sender.get_textBoxControl().value;
            $('#TextBox1').val("You entered: " + newValue);
        }
    });
});


View Page Source on modified Page (Not Working) to find control names
<head>
 <title="xxx"></title>

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="javascript2.js"></script>
    <link href="/WebResource.axd?d=c8_VgmWcKiDW3UhZXW3fdoIDZ9PA1vFl6xd-I-doFr1-b5nIUnd2QB0hVFZfs05Yaet7FQtVYD1v82Bb3tmB6pi2u_hsazhM7fdFOoSoZsMoFhet1syXyzLonl0XYu8JD8mSWTgkHsQRaP7V3I5EPA2&t=636555930634244069" type="text/css" rel="stylesheet" /><link href="/WebResource.axd?d=UT1Cj7SEzX8U-GEgOjD-q-uAvL1lhgJwhyoq55yRO8f994bH9Gts8yp6ytMieeH8QG6X7Gl6NbBYnmoVIPJVod06qYO9hCQNflvfGj0u0p2mbscQIs4D5BawDxSNlQmVG-5n140g3a_5wKRIhy31lA2&t=636555930634244069" type="text/css" rel="stylesheet" /><title>
	Home Page
</title></head>

    <form method="post" action="./" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="HaaItpdn//nkbAfTP30RBjjl0F3E7ZoFv4R/o9giKofWEHCF9arv37g03YgSd6MIvYh0kpxW6k+drR6pPsOSYRWHnXy7kWPsjShE+ax/O4ExDsLpHgJ0munTWb6p662pGhlN5NQx2fwiWmatSrtfvpckf0i/pR285OK5sznRG6OdOe8Q8PMak6/RV+glWE8skL7TPLxK4pP/eUNgZOXZnrQ5xzwoTu+b8NiD4lmLlw9FS9+rkdv3x9scFp1qP1skbqlrtLtfTfPV2A3j6W9cjkXhPTFJA0zI0gmOrLzdDdVSWHgm/YYJdyszVUjaNtB5" />
</div>

<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>


<script src="/WebResource.axd?d=pynGkmcFUV13He1Qd6_TZJq21wjd1aI3u0fP7i2J298r67whLwVKV9_BLKO71YaPOKI1fT20FzC0RXmnGRjE1g2&t=636475834140000000" type="text/javascript"></script>


<script src="Scripts/WebForms/MsAjax/MicrosoftAjax.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>

<script src="Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=pVdHczR8HTv0TYtXLibFoMiTqkPQHZxDGKkk2jtHc3bD1jiCHfD3Q9zqGOh0s2S184GWcZIyQ-Ww0sKOd7Ob_cwNLXMddEor6PQvBcNrN5cJO-d5YFClYZqK8AjS_2oNjDVgl1TXTU8XToUQ1Z09lw2&t=5e95cc64" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=VXG5HWKmJ5VfT6XbkUxKRkC8SYBMyMSiKGYECeO2xcIqB_FbwXW0QgY0JpudDTcsipO6wBDTX1IegGijNFB3pP2PfAgtSqq4F-Z83T3iO3LfTv9iJp5vV1eTA4UlJm8g0&t=5e95cc64" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=-qISl4-OkT-7X02E4FisrzrfZBRp_tPFwTXjeTSan36RT5qQnB9zFi4j-i9bamVZnqfgKx7r83H7nDn_CrCpgKLU6s-PBlLvPLO1YTkuQh8lRk1ruT5eSd-J9xKoza720&t=5e95cc64" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=LpGQnoKUSgO3ODsBUs8GfTwPrJ6pVgiHAih8HL5udKOmgyIrNzWXPPYynPZNNJr6CXzF63hh5Q5XAXgFvcA2FPHwAxXRXWgtyWQ-UK7qe3_qeOMYZAcXopGP_33fq-Og0&t=5e95cc64" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=iC2sD0Al8A6ZX4AVmUco0RYoAtlgo5TBV6TFiWAd6LH5qk-aJqTJIsKhNqWCPQrxJ8SVlDX4x0GfZod1UTf4kqZwnOL0wecbIVKRly49Utj1pNQFu4dzMXh9TDqYSxAb0&t=5e95cc64" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=q85rlLsZEVu9loex9kzISDVNv1qQjWFuEfriuQ80OLW-l5Aou2CDnohXRN_B8aJsD_NA187RErzxxV_ecpDFPOaptp6vO_mIIg06XEKcXzfpd9pWVzurwG6LvHVHs-XD0&t=5e95cc64" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=9fVK6SOzqud8-CG5DRcWdckouF4OcEUL-01qekRpoKsyHvyFxKoc005-XRhB6WkaPW1G9qT49DFYdcP382_r3r9jGkIrLqO53QXEUljd7LkE8qkOKPK4BQKz10dAU7rk0&t=5e95cc64" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=sjnc2GCx94Cxb1ZyngUXYubruiBO2ntiQSyVvuggsIXESLLS5iuEyNeLKJpfAlwm_IKL7jT1ovlJ5HGlFXwWBGpiO2A0Hn7iuWRR6A49puItPYXscpCpOfM58MkYRNFe0&t=5e95cc64" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=y7O-5TXW_SlHOhGQigRN3pZdTma56JohwinprH6n-5BfmiXcHjLi31grDw025eSNLYLGZ3qvNEzl_4g9dO50xqdPnO2ig_Umqimq-MGmyci8WWHFfnL3hUSqBpy7Cd0U0&t=5e95cc64" type="text/javascript"></script>
     <script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ScriptManager1', 'form1', [], [], [], 90, '');
//]]>
</script>

       <h1>Test ComboBox</h1>

       <p>
            <div id="ComboBox1" style="display:inline;">
	<table id="ComboBox1_ComboBox1_Table" class="ajax__combobox_inputcontainer" style="border-width:0px;border-style:None;display:inline;position:relative;top:5px;">
		<tr>
			<td class="ajax__combobox_textboxcontainer"><input name="ComboBox1$ComboBox1_TextBox" type="text" id="ComboBox1_ComboBox1_TextBox" autocomplete="off" /></td><td class="ajax__combobox_buttoncontainer"><button id="ComboBox1_ComboBox1_Button" tabindex="-1" type="button"></button></td>
		</tr>
	</table><ul id="ComboBox1_ComboBox1_OptionList" class="ajax__combobox_itemlist" style="display:none;visibility:hidden;">
		<li>test1</li><li>test2</li><li>test3</li>
	</ul><input type="hidden" name="ComboBox1$ComboBox1_HiddenField" id="ComboBox1_ComboBox1_HiddenField" value="0" />
</div>
            <input name="TextBox1" type="text" value="Please select a value from the dropdown box" id="TextBox1" style="background-color:#CCFFCC;height:21px;width:530px;" />
            <div id="ComboBox2" style="display:inline;">
	<table id="ComboBox2_ComboBox2_Table" class="ajax__combobox_inputcontainer" style="border-width:0px;border-style:None;display:inline;position:relative;top:5px;">
		<tr>
			<td class="ajax__combobox_textboxcontainer"><input name="ComboBox2$ComboBox2_TextBox" type="text" id="ComboBox2_ComboBox2_TextBox" autocomplete="off" /></td><td class="ajax__combobox_buttoncontainer"><button id="ComboBox2_ComboBox2_Button" tabindex="-1" type="button"></button></td>
		</tr>
	</table><input type="hidden" name="ComboBox2$ComboBox2_HiddenField" id="ComboBox2_ComboBox2_HiddenField" value="-1" />
</div>
            <p>
                <input type="submit" name="Button1" value="Next" id="Button1" style="color:Green;width:188px;" />
            </p>
                <p>
                <input type="submit" name="Button2" value="Button 2" id="Button2" style="width:188px;" />
            </p>
        
<div class="aspNetHidden">

	<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="CA0B0334" />
	<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="2clXZUv+XzBp3/H1iyUbfyUGabmvzsI2xiuXZsi+PKCPi1mv96d4wLhk5aP+FYh1b7I4dfPjL7K09CUSOMaGOuSmVK+eapK3YFkSwdb6Rc9rIRAbiPT2lUXy4Is8rg87N47wNzArHnw4NhHWjAqb5kXOR57R3W94hT85bNaAfY98dKFLvHBWcg9+GGWj5+jhXYD8y0s7yK45f98Ynj+6Iwyba1BF51lW/I2gZEr17s0LxXLgHFSY6KA+Ja+0y9zX" />
</div>

<script type="text/javascript">
//<![CDATA[
Sys.Application.add_init(function() {
    $create(Sys.Extended.UI.ComboBox, {"autoCompleteMode":0,"buttonControl":$get("ComboBox1_ComboBox1_Button"),"comboTableControl":$get("ComboBox1_ComboBox1_Table"),"dropDownStyle":1,"hiddenFieldControl":$get("ComboBox1_ComboBox1_HiddenField"),"optionListControl":$get("ComboBox1_ComboBox1_OptionList"),"textBoxControl":$get("ComboBox1_ComboBox1_TextBox")}, null, null, $get("ComboBox1"));
});
Sys.Application.add_init(function() {
    $create(Sys.Extended.UI.ComboBox, {"autoCompleteMode":0,"buttonControl":$get("ComboBox2_ComboBox2_Button"),"comboTableControl":$get("ComboBox2_ComboBox2_Table"),"dropDownStyle":0,"hiddenFieldControl":$get("ComboBox2_ComboBox2_HiddenField"),"optionListControl":$get("ComboBox2_ComboBox2_OptionList"),"selectedIndex":-1,"textBoxControl":$get("ComboBox2_ComboBox2_TextBox")}, null, null, $get("ComboBox2"));
});
//]]>
</script>
</form>


What I have tried:

Tried googling answer and tried many variation of comboBox1 control name without success
Posted
Updated 5-Mar-18 10:30am

1 solution

The ID that is set when you write your page is not the ID that is used when it is displayed on the client, the client id is generated by ASP for use in client code, refer to the following link; ASP.NET Web Server Control Identification[^]
To access your control, you can either use the Client Id or code within the page to access the control as follows;
JavaScript
var myCombo = $find("<% =ComboBox1.ClientID %>");

I understand this is a "test" but you should use a proper naming convention, ComboBox1 is not descriptive & as you can see when you View Source, the naming container prefixes the actual control name

As per your comment. The DOM needs to be parsed before you can access objects, to ensure the page is ready you can move your script tags to the bottom of the page, immediately before the closing body tag - refer;
javascript - document.getElementByID external or inline? - Stack Overflow[^]

Kind Regards
   
v2
Comments
PClarkeirl 10-Mar-18 15:36pm
   
unfortunately,
when I put your suggested line into the javascript

var myCombo = $find("<% =ComboBox1.ClientID %>");

it returns null.
an0ther1 11-Mar-18 17:25pm
   
I would suggest that your function is being called before the DOM has been parsed. Move your script tag to the bottom of the page before the closing body tag - solution updated

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900