Search code examples
javascriptjqueryknockout.jsdatepickerknockout-mapping-plugin

Bind datepicker on dynamic textbox with knockout js binding


Hello I am using knockout with ASP.NET MVC in my in house project.

I have one form page (Transaction page) that consist no. of clients in grid and based on click I am creating arrayobject in knockout and bind the table rows accordingly.

In the table I have one field date at first column and want to open datepicker when focus comes on that column.

But the problem I am facing now is whenever I change client selection it updates the tables transaction list and datepicker is not coming on the textbox I want.

Knockout binding in HTML:

<table id="idTblTranItems" class="table table-striped table-bordered table-hover table-green dataTable" aria-describedby="dtAllClients_info">
                                    <thead>
                                        <tr class="btn-primary">
                                            <th style="text-align:center">Date<br /> (MM/dd/YYYY)</th>
                                            <th style="text-align:center">Column2</th>
                                            <th style="text-align:center">Column3</th>
                                            <th colspan="2" style="text-align:center">Column4($)</th>
                                            <th style="text-align:center">Tax Column5</th>
                                            <th style="text-align:center">Tax Column6($)</th>
                                            <th style="text-align:center">Net Column7($)</th>
                                            <th style="text-align:center">Notes</th>
                                            <th style="text-align:center">More</th>
                                            <th style="text-align:center">Delete</th>
                                        </tr>
                                    </thead>
                                    <tbody data-bind="foreach: TransactionList" id="tbodyTransactionsNew">
                                        <tr>
                                            <td>
                                                <input class="form-control TransactionDate" type="text" data-bind="value: TransactionDate}" />
                                            </td>
                                            <td>
                                                <input type="text" class="form-control" data-bind="value: column2" />
</td>
                                            <td>
                                                <input type="text" class="form-control" data-bind="value: column3" />
                                            </td>
                                            <td>
                                                <input type="text" class="form-control" data-bind="value: column4" />

                                            </td>
                                            <td style="width:40px; border-left:none">
                                               <input type="text" class="form-control" data-bind="value: column5" />
                                            </td>
                                            <td>
                                                <input type="text" class="form-control" data-bind="value: column6" />
                                            </td>
                                            <td>
                                                <input type="text" class="form-control" data-bind="value: column7" />
                                            </td>
                                            <td>
                                                <input type="text" class="form-control NetAmount" data-bind="value: column8" />
                                            </td>
                                            <td>
                                                <textarea style="height:34px" class="form-control" data-bind="value: column9"></textarea>
                                            </td>
                                            <td>
                                                <textarea style="height:34px" class="form-control" data-bind="value: column10"></textarea>
                                            </td>
                                            <td>
                                                <textarea style="height:34px" class="form-control" data-bind="value: column11"></textarea>
                                            </td>
                                        </tr>
                                </table>

my js:

function TransactionVM(vm) {
            var self = this;
            self.TransactionList = ko.observableArray([]);
            self.Transactionclone = ko.observable();
            self.AccountId = ko.observable();

if (vm.TransList().length > 0) { for (var i = 0; i < vm.TransList().length; i++) { var transaction = new TransactionObj(vm.TransList()[i], vm.Accounts(), vm.Taxcodes()); self.TransactionList.push(transaction); } }

            $('.TransactionDate').datepicker({
                    autoclose: true,
                    format: 'mm/dd/yyyy',
                    startDate: date
                });
}

ko.applyBindings(new TransactionVM(ko.mapping.fromJS(transactionlist)));

You can see I have TransactionDate class binding datepicker but when I click on the textbox datepicker is not coming and in above datepicker initialisation I have for loop where I actually created the new objects of TransactionObj viewmodel.

Don't know how I can do this it's big issue for me I also tried this article as well but not helpful I have multiple textboxes and I can add also new Transaction as well and want datepicker on newly created textbox as well.

It is humble request to create jsfiddle so I can understand easily cause I have just started knockout js thank you.

enter image description here


Solution

  • You can create a custom ko binding for the datepicker which will be called when the control is databound.

    e.g.

    ko.bindingHandlers.datePicker = {
      init: function(element, valueAccessor) {
        var $element = $(element);
        $element
          .datepicker({
            autoclose: true,
            format: 'mm/dd/yyyy'
          });
      },
      update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var $element = $(element);
        $element.datepicker("setDate", value);
      }
    };
    
    function TransactionVM(vm) {
      var self = this;
      self.TransactionList = ko.observableArray([]);
    
      self.loadList = function(transactions) {
        self.TransactionList([]);
        transactions.forEach(function(transaction) {
          self.TransactionList.push(transaction);
        });
      };
    }
    
    var vm = new TransactionVM();
    ko.applyBindings(vm);
    
    var iteration = 1;
    function addData() {
      var transactions = [];
      for (var i = 0; i < 10; i++) {
        transactions.push({
          TransactionDate: new Date(),
          column2: "testing round " + iteration + " item " + i
        });
      }
      vm.loadList(transactions);
      iteration++;
    }
    
    $("#add").click(addData);
    <link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
    
    <table id="idTblTranItems" class="table table-striped table-bordered table-hover table-green dataTable" aria-describedby="dtAllClients_info">
      <thead>
        <tr class="btn-primary">
          <th style="text-align:center">Date<br /> (MM/dd/YYYY)</th>
          <th style="text-align:center">Column2</th>
        </tr>
      </thead>
      <tbody data-bind="foreach: TransactionList" id="tbodyTransactionsNew">
        <tr>
          <td>
            <input class="form-control TransactionDate" type="text" data-bind="datePicker: TransactionDate" />
          </td>
          <td>
            <input type="text" class="form-control" data-bind="value: column2" />
          </td>
        </tr>
    </table>
    <button id="add">Add</button>