Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enter key enable using knockout and javascript function

i have an html textbox with onkeypress event to send message like below

<input type="text" data-bind="attr:{id: 'txtDim' +  $data.userID, onkeypress: $root.sendMsg('#txtDim' +  $data.userID, $data)}" />

I have written javascript function to to send message while preesing enter button like below:

self.sendMsg = function (id, data) {
    $(id).keydown(function (e) {
        if (e.which == 13) {
            //method called to send message
            //self.SendDIM(data);
        }
    });
};

In my case i have to press enter button 2 times to send the message. 1: keypress call self.sendMsg 2: keypress call self.SendDIM

But i need to send message on one keypress only. It can be done in plain javascript only. But i need viewmodel data, so applied in data-bind. So not working fine.

like image 472
akeeseth Avatar asked Jan 12 '13 06:01

akeeseth


2 Answers

The reason you need to press enter twice is that your sendMsg method is only attaching a handler to the keydown event. This handler is then invoked on the second button press.

A better approach would be to write a custom binding handler that attaches the event handler and passes the view model through:

ko.bindingHandlers.returnAction = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel) {

    var value = ko.utils.unwrapObservable(valueAccessor());

    $(element).keydown(function(e) {
      if (e.which === 13) {
        value(viewModel);
      }
    });
  }
};

You can see a running example here

like image 57
Steve Greatrex Avatar answered Oct 20 '22 12:10

Steve Greatrex


I have added keypress event like below to textbox

 <input type="text" data-bind="attr:{id: 'txtGoalsheetNote' +  $data.userID}, event:{keypress: $root.SendMsg}" />

And in javascript i have added the following method by keeping event as a parameter

 self.SendMsg= function (data, event) {
    try {
        if (event.which == 13) {
            //call method here
            return false;
        }
        return true;
    }
    catch (e)
{ }
}

Then its work.

like image 38
akeeseth Avatar answered Oct 20 '22 12:10

akeeseth