0

I tried all possible ways to add javascript code to my dynamically created control a date textbox but it is not working. I need to add multiple scripts like searchable dropdownlist and datepicker for date textbox. I am creating control on Page_Init and then attaching javascript on Page_Load but it is not working. Can somebody help, please? Thanks.

protected void Page_Init(object sender, EventArgs e)
{
    CreateControls();
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (fieldtype == "date")
            {
                string javaScriptString = @"function attachJSScript() {";
                javaScriptString += @"$('#<%= " + str + ".ClientID %>').datepicker({ dateFormat: 'dd/mm/yy' }).val();";
                javaScriptString += @"}";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "attachJSScript", javaScriptString, true);
            }
        }
    }
}

When I view the page source, it shows

<script type="text/javascript">
//<![CDATA[
function attachJSScript() {$('#<%= txt_1_date_yes.ClientID %>').datepicker({ dateFormat: 'dd/mm/yy' }).val();}//]]>
</script>

I added this code for dropdownlist dynamically created control but it is not working either. Same code I used for the controls in aspx pages and that works.

enter image description here

Aqib Chattha
  • 197
  • 11
Raja
  • 131
  • 2
  • 16
  • Don't use directives (`<%= .. %>`) when writing the JavaScript string. As evident, they "don't work" (and are not needed) in that context. Instead, emit the control's *actual* ClientID so that it might look like `$("#the_controls_client_id").datepicker..` – user2864740 Dec 27 '21 at 05:40
  • What does the html for the control look like the rendered? How are you creating the date text box? Where is the variable `fieldType` coming from? You could probably bind the date picker with `$("[type=date]").datepicker()` – Jon P Dec 27 '21 at 05:41
  • Take a look : https://stackoverflow.com/questions/7046565/inject-javascript-from-asp-net-code-behind-files AND https://stackoverflow.com/questions/666519/difference-between-registerstartupscript-and-registerclientscriptblock and https://stackoverflow.com/questions/53976817/c-sharp-asp-net-webform-add-js-and-run-it-from-code-behind – AliNajafZadeh Dec 27 '21 at 05:55
  • @user2864740 I am using on other pages like this but it is on aspx page and registering on aspx.cs page like this and it is working fine. private void ReAttachJSScript() { ScriptManager.RegisterStartupScript(this, GetType(), "ataachJavaScript", "ataachJavaScript();", true); } I have to create dynamic controls and this need to by from code behind – Raja Dec 27 '21 at 06:44

0 Answers0