locked
Unable to bind date to input type date using jquery RRS feed

  • Question

  • User739135361 posted

    Hi, 

    I am using a modal pop up to bind data from data- properties as show  in the below post

    https://forums.asp.net/t/2163108.aspx?Opening+Bootstrap+Modal+pop+up+from+controller

    I am able to bind All controls from db values such as drop down, text box , text area. However, input type = "date" dosent bind. Specifically in Crome.  Here is the data property 

    data-identifieddate ="@item.IdentifiedDate.ToShortDateString()"
    data-expecteddate ="@item.ExpectedDate.ToShortDateString()"
    data-duedate ="@item.DueDate.ToShortDateString()"

    <input type="date" id="txtIdentifiedDate" name="IdentifiedDate" class="form-control" />

    <input type="date" id="txtExpectedDate" name="ExpectedDate" class="form-control" />

    <input type="date" id="txtDueDate" name="DueDate" class="form-control" />

    Here is the JQuery 

    var Idendate = button.data('identifieddate');
    var ExpDate = button.data('expecteddate');
    var Duedate = button.data('duedate');

    $("#txtIdentifiedDate").val(Idendate);
    $("#txtExpectedDate").val(ExpDate);
    $("#txtDueDate").val(Duedate);

    Any specific reason why it works in IE and not in crome. When I use developer tool even in IE the value is actually not set. It is rendered as 

    <input name="IdentifiedDate" class="form-control" id="txtIdentifiedDate" type="date"> but it has correct value  though. Same is the case with crome but it dosent render any values. I have debuged and i get the values in js its just not rendering.

    Any specific reason?

    Regards,

    Nizam

     

    Monday, April 20, 2020 5:40 PM

All replies

  • User475983607 posted

    Hi, 

    I am using a modal pop up to bind data from data- properties as show  in the below post

    https://forums.asp.net/t/2163108.aspx?Opening+Bootstrap+Modal+pop+up+from+controller

    I am able to bind All controls from db values such as drop down, text box , text area. However, input type = "date" dosent bind. Specifically in Crome.  Here is the data property 

    data-identifieddate ="@item.IdentifiedDate.ToShortDateString()"
    data-expecteddate ="@item.ExpectedDate.ToShortDateString()"
    data-duedate ="@item.DueDate.ToShortDateString()"

    <input type="date" id="txtIdentifiedDate" name="IdentifiedDate" class="form-control" />

    <input type="date" id="txtExpectedDate" name="ExpectedDate" class="form-control" />

    <input type="date" id="txtDueDate" name="DueDate" class="form-control" />

    Here is the JQuery 

    var Idendate = button.data('identifieddate');
    var ExpDate = button.data('expecteddate');
    var Duedate = button.data('duedate');

    $("#txtIdentifiedDate").val(Idendate);
    $("#txtExpectedDate").val(ExpDate);
    $("#txtDueDate").val(Duedate);

    Any specific reason why it works in IE and not in crome. When I use developer tool even in IE the value is actually not set. It is rendered as 

    <input name="IdentifiedDate" class="form-control" id="txtIdentifiedDate" type="date"> but it has correct value  though. Same is the case with crome but it dosent render any values. I have debuged and i get the values in js its just not rendering.

    Any specific reason?

    Regards,

    Nizam

     

    You've defined the input as a date type.

    <input name="IdentifiedDate" class="form-control" id="txtIdentifiedDate" type="date">

    The expected date format is yyyy-MM-dd.  

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date

    Change the date format from...

    data-identifieddate ="@item.IdentifiedDate.ToShortDateString()"

    To

    data-identifieddate ='@item.IdentifiedDate.ToStirng("yyyy-MM-dd")'

    Monday, April 20, 2020 6:16 PM
  • User665608656 posted

    Hi,  N1ZAM

    Your date cannot be displayed on Google Chrome because your date does not match the date format supported by the browser.

    In addition, you need to pay attention to the method named "ToShortDateString ()” which is not controlled by itself. In fact, it is affected by the location and artificial setting.

    I suggest you better format the date so that you can avoid problems.

    More details, you could refer to below code:

    @*your code*@
    
    <input type="date" id="txtIdentifiedDate" name="IdentifiedDate" class="form-control" />
    
    <input type="date" id="txtExpectedDate" name="ExpectedDate" class="form-control" />
    
    <input type="date" id="txtDueDate" name="DueDate" class="form-control" />
    
     
    
    @*test*@
    
    <input type="date" id="test1"/>
    
    <input type="date" id="test2" />
    
    @section scripts
    
        {
    
        <script>
    
            //supplement this method:IE does not support the padStart method
    
            //padStart(): If a string is not longer than the specified length, it will be completed at the head.
    
            //The first parameter is used to specify the minimum length of the string, and the second parameter is used to complete the string.
    
            if (!String.prototype.padStart) {
    
                String.prototype.padStart = function padStart(targetLength, padString) {
    
                    targetLength = targetLength >> 0; //truncate if number or convert non-number to 0;
    
                    padString = String((typeof padString !== 'undefined' ? padString : ' '));
    
                    if (this.length > targetLength) {
    
                        return String(this);
    
                    }
    
                    else {
    
                        targetLength = targetLength - this.length;
    
                        if (targetLength > padString.length) {
    
                            padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
    
                        }
    
                        return padString.slice(0, targetLength) + String(this);
    
                    }
    
                };
    
            }
    
            function dateFormat(fmt, date) {//Format date
    
                let ret;
    
                const opt = {
    
                    "y+": date.getFullYear().toString(),        // year
    
                    "m+": (date.getMonth() + 1).toString(),     // month
    
                    "d+": date.getDate().toString(),            // day
    
                    // If you need to format other characters, you can continue to add, but it must be converted into a string.
    
                };
    
                for (let k in opt) {
    
                    ret = new RegExp("(" + k + ")").exec(fmt);
    
                    if (ret) {
    
                        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
    
                    };
    
                };
    
                return fmt;
    
            }
    
            //your code
    
            //show you show you these three forms of output.
    
            var Idendate = "2020-04-21";
    
            var ExpDate = "2020/04/21";
    
            var Duedate = "2020.04.21";
    
            $("#txtIdentifiedDate").val(Idendate);
    
            $("#txtExpectedDate").val(ExpDate);
    
            $("#txtDueDate").val(Duedate);
    
     
    
            //test
    
            //The date is output in the format required by Google Chrome
    
            var date = new Date();
    
            console.log(date.toDateString());
    
            $("#test1").val(date.toDateString());
    
            $("#test2").val(dateFormat("yyyy-mm-dd", date));
    
        </script>
    
    }

    Here is the result:

    Best Regards,

    YongQing.

    Tuesday, April 21, 2020 6:15 AM
  • User739135361 posted

    Hi All, 

    Thanks for your response. Instead of binding those many values from a data- properties of a button, the requiremen have changed to get the values based on Ajax Call. I am able to bind all values except date. So back to square one. I have tried few approaches but date in Crome is displayed in a different format and different form date in IE. Is that normal ? 

    var iddt = new Date(parseInt(IdentifiedDate.substr(6)));
    $("#txtIdentifiedDate").val(formatDate(iddt)); 

    function formatDate(_date) {
    var currentTime = new Date(_date)
    var month = currentTime.getMonth() + 1
    var day = currentTime.getDate()
    var year = currentTime.getFullYear()
    return month + "/" + day + "/" + year;
    //return year+ "-" + month + "-" + day;
    }

    In both the cases date dosent bind in Crome, even if I return  year+ "-" + month + "-" + day format. 

    Tuesday, April 21, 2020 7:37 AM
  • User475983607 posted

    N1ZAM

    Thanks for your response. Instead of binding those many values from a data- properties of a button, the requiremen have changed to get the values based on Ajax Call. I am able to bind all values except date. So back to square one. I have tried few approaches but date in Crome is displayed in a different format and different form date in IE. Is that normal ? 

    Yes this is normal and expected.  This fact is clearly and openly discussed in the links provided above.  Setting the input type to date causes the browser to render their own version of a date picker.  Do not set the type to date and use a jQuery date picker if you want a consistent UI.

    N1ZAM

    var iddt = new Date(parseInt(IdentifiedDate.substr(6)));
    $("#txtIdentifiedDate").val(formatDate(iddt)); 

    function formatDate(_date) {
    var currentTime = new Date(_date)
    var month = currentTime.getMonth() + 1
    var day = currentTime.getDate()
    var year = currentTime.getFullYear()
    return month + "/" + day + "/" + year;
    //return year+ "-" + month + "-" + day;
    }

    In both the cases date dosent bind in Crome, even if I return  year+ "-" + month + "-" + day format. 

    Your code has bugs.  I assume here....

    var iddt = new Date(parseInt(IdentifiedDate.substr(6)));

    ...Then you create another new Date in the function...

    function formatDate(_date) {
    var currentTime = new Date(_date)

    ...But there is not enough information to debug your code.   I recommend returning the date format from the Action rather than using JavaScript since it is one line of code in C#.

    Tuesday, April 21, 2020 10:59 AM
  • User739135361 posted

    Hi,

    I am now able to populate date in Modal Pop up in crome. Earlier it was blank, now its coming as expected. How ever I ran into another issue when the value was not getting updated in a model. 

    data is the object which has entire model. 

    var edate = foo(data.EndDate);

    $("#txtEndDate").val(edate);

    function foo(dt) {

    var dateString = dt.substr(6);
    var _d = new Date(parseInt(dateString));
    var dd = _d.getDate();
    var MM = _d.getMonth() + 1;
    if (parseInt(MM) < 9)
    MM = "0" + MM;
    var yyyy = _d.getFullYear();
    return yyyy + "-" + MM + "-" + dd;

    }

    However, when I post the form, startdate and end date are "01/01/001". I tried to check if I am getting the values in form collection. Infact I am getting the values inform collection prefixed with a comma for instance fc["StartDate"]=",2020-06-10". Any reason for this? May thats the reason Model is not getting updated

    Wednesday, April 22, 2020 12:14 PM
  • User475983607 posted

    However, when I post the form, startdate and end date are "01/01/001". I tried to check if I am getting the values in form collection. Infact I am getting the values inform collection prefixed with a comma for instance fc["StartDate"]=",2020-06-10". Any reason for this? May thats the reason Model is not getting updated

    This is a very common issue reported in these forums and it usually means the model property names do not match the input names.    You did not share the relevant code so we can only guess but that's generally the issue.  I created simple test that you can see below and the model binding works as expected.

    <form method="post">
        <input type="date" name="StartDate" value="2020-04-22" />
        <input id="Submit1" type="submit" value="submit" />
    </form>
        public class TestVm
        {
            public DateTime StartDate { get; set; } 
        }
            [HttpGet]
            public IActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            public IActionResult Index(TestVm model)
            {        
                return Json(model);
            }

    Results

    {
      "startDate": "2020-04-22T00:00:00"
    }

    Wednesday, April 22, 2020 12:26 PM