简体   繁体   中英

How can I get dynamic Timepicker values in javascript

So, I'm using Kendo UI MVC where I want to create a type of request. However, the number of user controls is dynamic and depends of how many requests of that type the user wants to make. So to create them, I have this:

@while(number!=numberAdds){
<br />
    <label style="margin-right:1em;margin-top:1.5em">Start time:</label>
    @(Html.Kendo().TimePicker()
          .Name("startTime"+(number+1))
          .Min("8:00")
          .Max("19:50")
          .Interval(10)
)

    <label style="margin-left:2.5em; margin-right:1em">End time:</label>
    @(Html.Kendo().TimePicker()
          .Name("endTime"+(number+1))
          .Min("8:10")
          .Max("20:00")
          .Interval(10))

      number++;}

And it works. Now, when I click the submit button, what I'm trying to do is to create an array of StartTimes and EndTimes so I can send it via Ajax Post to the controller. However, I'm not able to do so, because of the TimePickers ID. I'm trying to do something like this:

   $(document).on("click", "#confirm-request", function (e) {
        var date = $("#date").data("kendoDatePicker").value();
        var stringDate = kendo.toString(date, "yyyy-MM-dd");
        var number = 0;
        var numberAdds = parseInt(document.getElementById("number-adds").textContent);
        var timeStartStrings = new Array();
        var timeEndStrings = new Array();

        for (number; number < numberAdds; i++) {
            var startTime = $("#startTime"+number).data("kendoTimePicker");
            var endTime = $("#endTime"+number).data("kendoTimePicker");
            var timeStartString = kendo.toString(startTime.value(), 'yyyy-MM-dd hh:mm');
            var timeEndString = kendo.toString(endTime.value(), 'yyyy-MM-dd hh:mm');
            timeStartStrings[number] = timeStartString;
            timeEndStrings[number] = timeEndString;
        }

However I can't get values for StartTime and EndTime, I always get undefined and I know it's because of $("#startTime"+number).data("kendoTimePicker");

What can I do? Thanks :)

Is your number -variable in the razor code (top code block) starting initially with -1 (because of .Name("startTime"+(number+1)) ? Otherwise your javascript code will on its first iteration try to find $("#startTime0") without it existing. This probably leads to an error and thus stopping the execution of the JS-function.

So please check the names existing in your DOM vs the names questioned by Javascript and make sure, that they align properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM