This is a migrated thread and some comments may be shown as answers.

Dynamically loaded RadComboBox using JavaScript

12 Answers 597 Views
Ajax
This is a migrated thread and some comments may be shown as answers.
Eric Schuler
Top achievements
Rank 1
Eric Schuler asked on 18 Feb 2011, 12:48 AM
Hi,

I have trouble to set selected value for a RadComboBox using Javascript.

I think the trouble I have is because the RadComboBox is loaded dynamically in a user control.

Actually the whole website is built based on multiple user controls with AJAX, which mean, there is no post back.

I tried:
function JSSelect() {
    var combo = $find("<%= RadComboBox1.ClientID %>");
    var itm = combo.findItemByValue('04');
    itm.select();
}

I want to call this function at a proper time when the user control which contain my RadComboBox is loaded. But I think it's because of "<%=" and "%>", the page will try to find RadComboBox1 first when the page is first request, but at this time, the user control which contains my RadComboBox has not been loaded. How can I solve this problem?

12 Answers, 1 is accepted

Sort by
0
Helen
Telerik team
answered on 22 Feb 2011, 12:16 PM
Hi Eric,

Did you try to register the script with the ScriptManager.RegisterStartupScript() server method?
You may find helpful the following forum posts:

http://www.telerik.com/community/forums/aspnet-ajax/ajax/how-to-insert-javascript-after-an-ajax-response.aspx


http://www.telerik.com/community/forums/aspnet-ajax/ajax/scriptmanager-registerstartupscript-and-the-radajaxpanel.aspx


Regards,
Helen
the Telerik team
Registration for Q1 2011 What’s New Webinar Week is now open. Mark your calendar for the week starting March 21st and book your seat for a walk through all the exciting stuff we ship with the new release!
0
Harshad
Top achievements
Rank 1
answered on 01 Feb 2012, 01:20 AM
Hi Telerik,

I facing a similar issue but different way and I tried the solution which you proposed but it is not working.
I am doing a migration from VS 2005(RAD 2003)  to 2010  (RAD 2010  Q3 ASP.NET Ajax) -  so I can not change the componets in my old code except the modification which is reqired to work RAD 2010 .
here the issue is Radcombobox is not loading properly when it calls. it is always showing null , I have used
ScriptManager.RegisterStartupScript as per your suggestion but it didn't work, I have created a sample project both in 2010 (with RAD 2010)  & 2005 (with RAD 2003).   it is working perfectly in 2005 but not in 2010- can you please help on this,
I have attached both projects  along with this post
code which is working in 2005
default.aspx

<%

@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 <%@ Register Assembly="RadComboBox.Net2" Namespace="Telerik.WebControls" TagPrefix="radC" %>

 <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 < html xmlns="http://www.w3.org/1999/xhtml" >

 <head runat="server">  

 

<title>Untitled Page</title>

 </head>

 <body>

 <form id="form1" runat="server">

 <div>

 <table>

 <tr>

 <td><span id="comboHolder">

 </span>

 <radC:RadComboBox

 ID="rcbDateRangePicker"  runat="server" OnClientBlur="ChangeDate" Height="190px" Width="110px"> </radC:RadComboBox>

 </td> <td><asp:Image ID="imgBtn" runat="server" /> </td>

 </tr
</table>

 </div>

 </form>

 </body>

 </html>

default.aspx.cs

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using Telerik.WebControls;

using System.Text;

public partial class _Default : System.Web.UI.Page

 {

        protected void Page_Load(object sender, EventArgs e)

        {

            RadDatePicker startDateControl = new RadDatePicker();

            RadDatePicker endDateControl = new RadDatePicker();

            if (!IsPostBack)

            {

                 imgBtn.Attributes.Add("onclick", "TogglePicker();");

                 DateTime now = DateTime.Now;

                 DateTime lastMonth = DateTime.Now.AddMonths(-1);

                rcbDateRangePicker.Items.Add(new RadComboBoxItem("None"));

                AddDate(now, now, "Today");

                AddDate(now.AddDays(-30), now, "Last 30 Days");

                AddDate(now.AddDays(-45), now, "Last 45 Days");

               //set default

                 (startDateControl as RadDatePicker).DbSelectedDate = DateTime.Now;

                 (endDateControl as RadDatePicker).DbSelectedDate = DateTime.Now;

             }

 

             StringBuilder builder = new StringBuilder();

 builder.AppendLine(

"<script type=\"text/javascript\">");

 builder.AppendLine("var combo = null;");

 builder.AppendLine("try { combo = " + rcbDateRangePicker.ClientID + " } catch(err){}");

 builder.AppendLine(@"function TogglePicker()

 {

if(combo==null)

{

alert('this object is empty');

var itemSelected = combo.SelectedItem.Value;

alert(itemSelected)

}

else

{

alert('this object is not empty');

var itemSelected = combo.SelectedItem.Value;

alert(itemSelected)

}

}

function ChangeDate()

{

if(combo==null)

{

alert('this object is empty');

var itemSelected = combo.SelectedItem.Value;

}

else

{

alert('this object is not empty');

}

}

"

 );

 

builder.AppendLine(

"</script>");

 if (!Page.ClientScript.IsClientScriptBlockRegistered("DateRangeScript"))

 Page.ClientScript.RegisterStartupScript(

 this.GetType(), "DateRangeScript", builder.ToString());

}

 

private void AddDate(DateTime startDate, DateTime endDate, string text)

 {

 RadComboBoxItem item = new RadComboBoxItem(text, text);

 item.Attributes.Add("StartDate", startDate.ToString());

 item.Attributes.Add("EndDate", endDate.ToString());

 if (text.Equals("Today") && !Page.IsPostBack)

 item.Selected = true;

rcbDateRangePicker.Items.Add(item);

}

}

 
================================================================================

code which is not working with 2010
default.aspx

 

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"

 CodeFile="Default.aspx.cs" Inherits="_Default" %>

 <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

 </asp:Content>

 <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

 <table>

 <tr>

 <telerik:RadScriptManager ID="radSctMgr" runat ="server">

 </telerik:RadScriptManager>

 <td><span id="comboHolder">

 </span>

 <telerik:RadComboBox ID="rcbDateRangePicker" runat="server" OnClientBlur="ChangeDate" Height="190px"  

Width="110px">

 </telerik:RadComboBox>

 </td>

 <td><asp:Image ID="imgBtn" runat="server" /> </td>

 </tr>

 </table>

 </asp:Content>

 default.aspx.cs

using System;
using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Text; 
using Telerik.Web.UI;

 public partial class _Default : System.Web.UI.Page

 {

 string someScript = string.Empty;

 protected void Page_Load(object sender, EventArgs e)

 {

       RadDatePicker startDateControl = new RadDatePicker();

   RadDatePicker endDateControl = new RadDatePicker();

if (!IsPostBack)

 {

imgBtn.Attributes.Add("onclick", "TogglePicker();");

DateTime now = DateTime.Now;

DateTime lastMonth = DateTime.Now.AddMonths(-1);

 rcbDateRangePicker.Items.Add(new RadComboBoxItem("None"));

 AddDate(now, now, "Today");

 AddDate(now.AddDays(-30), now, "Last 30 Days");

 AddDate(now.AddDays(-45), now, "Last 45 Days");

 //set default

 (startDateControl as RadDatePicker).DbSelectedDate = DateTime.Now;

 (endDateControl  as RadDatePicker).DbSelectedDate = DateTime.Now;

 }

StringBuilder builder = new StringBuilder();

 builder.AppendLine("<script type=\"text/javascript\">");

 builder.AppendLine("var comboCal = null;");

 builder.AppendLine("var comboCal = $find('" + rcbDateRangePicker.ClientID + "');");

 // builder.AppendLine("try { comboCal = $find(\"<%=" + rcbDateRangePicker.ClientID + " %>\") } catch(err){}");

 //builder.AppendLine("try { comboCal = " + rcbDateRangePicker.ClientID + " } catch(err){}");

 builder.AppendLine(@"function TogglePicker()

 {

if(comboCal==null)

{

alert('this object is empty');

var itemSelected = comboCal.SelectedValue;

alert(itemSelected);

}

else

{

alert('this object is not empty');

var itemSelected = comboCal.SelectedValue;

alert(itemSelected);

}

}

function ChangeDate()

{

if(comboCal==null)

{

alert('this object is empty');

var itemSelected = comboCal.SelectedValue;

}

else

{

alert('this object is not empty');

}

}

 ");

 

builder.AppendLine("</script>");

 //someScript = "Sys.Application.add_load(" + builder.ToString() + ");";

 //ScriptManager.RegisterStartupScript(Page, this.GetType(), "onload", someScript, true);

 if (!Page.ClientScript.IsClientScriptBlockRegistered("DateRangeScript"))

 Page.ClientScript.RegisterStartupScript( this.GetType(), "DateRangeScript", builder.ToString());

 }
private void AddDate(DateTime startDate, DateTime endDate, string text)

{

RadComboBoxItem item = new RadComboBoxItem(text, text);

item.Attributes.Add("StartDate", startDate.ToString());

 item.Attributes.Add("EndDate", endDate.ToString());

 if (text.Equals("Today") && !Page.IsPostBack)

 item.Selected = true;

 rcbDateRangePicker.Items.Add(item);

}

}

0
Ivana
Telerik team
answered on 01 Feb 2012, 06:29 PM
Hello,

When RadComboBox is placed inside a UserControl its client ID is changed. You could use the following method to find the control:
var comboJQueryObject = $telerik.$("[id$='_RadComboBox1']");
var combo = $find(comboJQueryObject.attr["id"]);
if(combo){
   combo.findItemByValue("04").select();
}

As for registering a client script from the server,  attached is a sample page showing how to do it. You could download it and give it a try locally.

I hope this is helpful.

All the best,
Ivana
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Harshad
Top achievements
Rank 1
answered on 04 Feb 2012, 01:30 AM
Thanks Ivana.
sorry for delayed reply since I was out of town.
I have tried the solution which you have attached and I am able to get the value if the function is calling from the control combobox ( using sender.get_text())  but here the issue is I am calling the Java script function from some other control ( say Button)  and that function required combobox object to be modified.
e.g from the attached file Test.aspx.cs   (I have tried with $Telerik  and even with direct controlID taken from view source)
I have modified few lines

string 

handlerClientItemsRequested = "function OnClientLoad(sender, args){ \n"

 //var comboCal= $find(""<%= RadComboBoxCategory.ClientID %>"");

+

" var comboCal = $find('" + RadComboBoxCategory.ClientID + "'); \n"

 " if(comboCal==null) { alert('this object is empty'); } else {alert('this object is not empty');} \n"

 " alert(comboCal.SelectedValue);" //not working

 " alert(sender.get_text()); \n" //this is working

 " \n"

 "}";
in this case comboCal is always Null ( just consider this function is calling from some other control or combobox itself - both ways it is not working)
I have created a proj even with out user control but in vein.  I am using Master pages.
Everything is fine with old version -- I have both proj created and is there any way to send the sample project to you- attachment of zip is not allowing here.
Thanks in Advance

0
Ivana
Telerik team
answered on 07 Feb 2012, 05:25 PM
Hello,

You could send us a sample project via a support ticket where attachments are allowed. Or, you could paste the definition of RadComboBox control and the code affected in here.

All the best,
Ivana
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
0
Harshad
Top achievements
Rank 1
answered on 07 Feb 2012, 06:05 PM

Thx Ivava,
I am Pasting the code below -   when I click on the button on the below project then the  combobox control is getting Null- but it is working in 2005  - so please let me know whether I missed anything here or should I use another method. ASPX (Default.aspx)   - used
ScriptManager as well as Client Script to register.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</
asp:Content>
<
asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<
table>
<
tr>
<
telerik:RadScriptManager ID="radSctMgr" runat ="server">
</
telerik:RadScriptManager>
<
td><span id="comboHolder">
</
span>
<
telerik:RadComboBox ID="rcbDateRangePicker" runat="server" OnClientBlur="ChangeDate"Height="190px"Width="110px">
</
telerik:RadComboBox></td><td><asp:Image ID="imgBtn" runat="server" /> </td></tr>
</
table></asp:Content>



default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Telerik.Web.UI;
public partial class
_Default : System.Web.UI.Page
{
string someScript = string.Empty;
protected void Page_Load(object sender,
EventArgs e)
{RadDatePicker startDateControl = new RadDatePicker();
RadDatePicker endDateControl = new RadDatePicker();
if (!IsPostBack)
{imgBtn.Attributes.Add(
"onclick", "TogglePicker();");
DateTime now = DateTime.Now;
DateTime lastMonth = DateTime.Now.AddMonths(-1);
rcbDateRangePicker.Items.Add(new RadComboBoxItem(
"None"));
AddDate(now, now,
"Today");
AddDate(now.AddDays(-30), now,
"Last 30 Days");
AddDate(now.AddDays(-45), now,
"Last 45 Days");
//set default
(startDateControl as RadDatePicker).DbSelectedDate = DateTime.Now;
(endDateControl as RadDatePicker).DbSelectedDate =
DateTime.Now;
}

 

StringBuilder builder = new StringBuilder();
builder.AppendLine(
"<script type=\"text/javascript\">");
builder.AppendLine(
"var comboCal = null;");
builder.AppendLine(
"var comboCal = $find('" + rcbDateRangePicker.ClientID + "');");
// builder.AppendLine("try { comboCal = $find(\"<%=" + rcbDateRangePicker.ClientID + " %>\") } catch(err){}");
//builder.AppendLine("try { comboCal = " + rcbDateRangePicker.ClientID + " } catch(err){}");
builder.AppendLine(@"function TogglePicker()
{
  if(comboCal==null)
  {
     alert('this object is empty');
     var itemSelected = comboCal.SelectedValue;
     alert(itemSelected);
  }
  else
  {
    alert('this object is not empty');
    var itemSelected = comboCal.SelectedValue;
    alert(itemSelected);
  }

}

function ChangeDate()
{
 if(comboCal==null)
 {
    alert('this object is empty');
    var itemSelected = comboCal.SelectedValue;
 }
 else
 {
   alert('this object is not empty');
 }
}
"
);
builder.AppendLine(
"</script>");
//someScript = "Sys.Application.add_load(" + builder.ToString() + ");";
//ScriptManager.RegisterStartupScript(Page, this.GetType(), "onload", someScript, true);
if (!Page.ClientScript.IsClientScriptBlockRegistered("DateRangeScript"))
Page.ClientScript.RegisterStartupScript(this.GetType(),
"DateRangeScript", builder.ToString());
}

 private void AddDate(DateTime startDate, DateTime endDate, string text)
 {
  RadComboBoxItem item = new RadComboBoxItem(text, text);
  item.Attributes.Add(
"StartDate", startDate.ToString());
  item.Attributes.Add(
"EndDate", endDate.ToString());
  if (text.Equals(
"Today") && !Page.IsPostBack) item.Selected = true;
   rcbDateRangePicker.Items.Add(item);
 }
}

--------------
Master(site.master.cs)
<
html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<
head runat="server">
<
title></title>
<
link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<
asp:ContentPlaceHolder ID="HeadContent" runat="server">
</
asp:ContentPlaceHolder>
</
head>
<
body><form runat="server"><div class="page"><div class="header"><div class="title">
<
h1>My ASP.NET Application</h1></div></div><div class="main"><asp:ContentPlaceHolder ID="MainContent" runat="server"/></div><div class="clear"></div></div>
<
div class="footer">
</
div>
</
form>
</
body></html>


---Config Files

 

<?xml version="1.0"?>

<!--

  For more information on how to configure your ASP.NET application, please visit

  http://go.microsoft.com/fwlink/?LinkId=169433

  -->

<configuration>

       <system.web>

              <compilation debug="true" targetFramework="4.0"/>

              <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">

                     <controls>

                           <add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI"/>

                           <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

</controls>

</pages>

    <httpHandlers>

      <remove verb="*" path="*.asmx"/>

      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>

      <add path="Telerik.Web.UI.WebResource.axd" verb="*" type="Telerik.Web.UI.WebResource, Telerik.Web.UI" validate="false"/>

    </httpHandlers>   

       </system.web> <system.webServer><modules runAllManagedModulesForAllRequests="true"/>

       </system.webServer>

</configuration>

0
Harshad
Top achievements
Rank 1
answered on 09 Feb 2012, 04:59 PM
Hi ,
I can provide you a very simple example.  in this below example I am getting "combo "  null can u please check what I missed from this.
if I use the Java script in aspx  or if I call the function from RadComboBox event then I am able to get  but I need to get the the object of RadComboBox from this structure - please help me to find out -Thx in advance.
Structure
-----------
1:controls in aspx
2:Java script in aspx.cs ( registering from Page Load) - Javascript Register control is Page
3:calling the Java script function from other control ( not from RadCombobox) for getting the object of RadComboBox.


Default.aspx
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
%> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head id="Head1" runat="server">  

<title></title> <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />

</head>

<body>  

<form runat="server" id="test">
<telerik:RadScriptManager ID="RadScriptManager1" runat ="server"> 
</telerik:RadScriptManager> 

<table><tr><td><telerik:RadComboBox ID="rcbDateRangePicker" runat="server" Height="190px" Width="110px"> </telerik:RadComboBox></td>

<td><asp:Image ID="imgBtn" runat="server" /> </td></tr>

</table> </form> </body> </html>

 

Default.aspx.cs
==================

using System;

using System.Web.UI;

using System.Text;

using Telerik.Web.UI;

public partial class _Default : System.Web.UI.Page

{

  protected void Page_Load(object sender, EventArgs e)

  {

    if (!IsPostBack)

    {

      imgBtn.Attributes.Add("onclick", "TogglePicker();");

      DateTime now = DateTime.Now;

      DateTime lastMonth = DateTime.Now.AddMonths(-1);

      rcbDateRangePicker.Items.Add(new RadComboBoxItem("None"));

      rcbDateRangePicker.Items.Add(new RadComboBoxItem("Today"));

     }

    StringBuilder builder = new StringBuilder();

    builder.AppendLine(@"function TogglePicker()

    {

       alert('inside Toggle');

       var combo = $find(""<%= rcbDateRangePicker.ClientID %>"");

       alert(combo.get_text());}");

  ScriptManager.RegisterStartupScript(Page, this.GetType(), "onloadOfDocument", builder.ToString(), true);

  }

}

 

0
Harshad
Top achievements
Rank 1
answered on 09 Feb 2012, 06:11 PM
Ok It worked   when I change the code to

 

" var combo = $find('"+ rcbDateRangePicker.ClientID + "'); \n"

 but I am always getting an error

 <script type="text/javascript">

 //<![CDATA[

 if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');

 //]]>

 </script>

 I have done all the option which is mentioned in the Telerik link http://www.telerik.com/help/aspnet-ajax/introduction-troubleshooting.html   but no luck 

 

 

 

 

 

0
Ivana
Telerik team
answered on 10 Feb 2012, 10:36 AM
Hi,

When registering JavaScript form code-behind the Page_Load event might be too late to do so. Instead try using the Page_Init event as it is shown in the sample page I have attached previously to this conversation.

As for the error you are getting, you could refer to this website discussing the same problem.

I hope this helps.

Greetings,
Ivana
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
0
Harshad
Top achievements
Rank 1
answered on 15 Feb 2012, 11:09 PM
Thx for your help Ivana,
RadComboBox issue has been resolved when I used the code the way which I mentioned in my previous post,  currently my website is running with out any issue but when I take ' view source ' it is showing Ajax Loading error I tried all the option but  still it is there  so  I am wondering whther it makes some other issue or not.

0
Ivana
Telerik team
answered on 20 Feb 2012, 09:47 PM
Hello Harshad,

What exactly do you mean by:
"...but when I take ' view source ' it is showing Ajax Loading error...".
Could you make a video of how do you reproduce this error? You could use the Jing tool to so.

Kind regards,
Ivana
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
0
Harshad
Top achievements
Rank 1
answered on 07 Mar 2012, 05:34 PM
Hi , As I mentioned earlier every thing got resolved --  the Issue of Ajax Loading error  was due to system issue and it got resolved after I restart my Machine.

Thanks for your Support.
Tags
Ajax
Asked by
Eric Schuler
Top achievements
Rank 1
Answers by
Helen
Telerik team
Harshad
Top achievements
Rank 1
Ivana
Telerik team
Share this question
or