Chatra
Chatra

Reputation: 3139

Jquery Select Equivalent in Knockout Js

I am new to Knockout and having tough time trying to resolve this.

I am trying to accomplish this Select functionality in Knockout. When I select the text, I want to highlight the border.

https://api.jquery.com/select/

Right now, in Knockout, I am able to highlight the border using click but when user selects the text directly in the textbox, Am unable to highlight the border.

Here is the html for that. There is lot going on in that textbox. If my question is not clear, Please ask so that I can explain better.

<input class="name" type="text"
data-bind="click: function (y, event) { $root.SelectedWay($parent.Way); $root.SelectChild(y, event); $(event.target).select(); },
typeahead: { 'source': $root.All(), 'sorter': $root.ColorSorter, 'updater': $root.UpdateSelectedColor, 'highlighter': $root.HighlightColor, 'matcher': $root.MatchColor },
css: { 'selected': Selected }, 
value: Name" />

Upvotes: 0

Views: 348

Answers (1)

Bryan Dellinger
Bryan Dellinger

Reputation: 5304

how about a custom binding. here is one where the border turns red using the jquery select

ko.bindingHandlers.jquerySelect = {
  init: function(element, valueAccessor, allBindingsAccessor) {
    $(element).select(function() {
      $(this).css("border", "5px solid red");
    });
    $(element).val(valueAccessor()());
  },
  //update the control when the view model changes
  update: function(element, valueAccessor, allBindingsAccessor) {
    $(element).val(valueAccessor()());
  }
};



function model() {
  var self = this;
  this.myObservable = ko.observable('hello world');
}

var mymodel = new model();

$(document).ready(function() {
  ko.applyBindings(mymodel);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-bind="jquerySelect: myObservable" />

Upvotes: 2

Related Questions