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

4
  • 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.. Commented Dec 27, 2021 at 5: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() Commented Dec 27, 2021 at 5:41
  • Take a look : stackoverflow.com/questions/7046565/… AND stackoverflow.com/questions/666519/… and stackoverflow.com/questions/53976817/… Commented Dec 27, 2021 at 5:55
  • @user2864740 I am using on other pages like this but it is on aspx page <script> function ataachJavaScript() { $("#<%= ddModule1.ClientID %>").select2(); $("#<%= txtFD.ClientID %>").datepicker({ dateFormat: 'dd/mm/yy' }).val(); } </script> 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 Commented Dec 27, 2021 at 6:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.