Binding input enter to function call using knockout - javascript

I'm trying to have an input element call a function when I press enter and use the value in the element:
<input id="searchQuery" placeholder="Search..." type="text" data-bind="value: searchQuery, valueUpdate: 'onkeydown', event: { keydown: searchQueryEntered }"/>
The function:
searchQueryEntered = function (value, event) {
if (event.keyCode == 13)
...do some stuff...
},
My function does get called, but searchQuery is never updated! I can't even type anything into the input. Somehow it's getting thrown out. What I'm trying to do seems pretty simple to me but I haven't been able to get it right.

To fix your input you need to return true from your keydown handler:
searchQueryEntered = function (value, event) {
if (event.keyCode == 13) {
...do some stuff...
}
return true;
}
Then you should use valueUpdate: 'afterkeydown' to make your model be updated after each keydown.
Check out this working example: http://jsfiddle.net/tabalinas/h4u8E/

Register a bindinghandler for the enter key
ko.bindingHandlers.onEnterKey = {
init: function(element, valueAccessor, allBindings, vm) {
ko.utils.registerEventHandler(element, "keyup", function(event) {
if (event.keyCode === 13) {
ko.utils.triggerEvent(element, "change");
valueAccessor().call(vm, vm);
}
return true;
});
}
};
then you can bind as follow onEnterKey: searchQueryEntered
see fiddle below
http://jsfiddle.net/NccZ8/2/

Related

Allowing Enter Key and Click Function to both run

I have the function:
$(document).on('click keypress', '.pTile:not(.join)', function (e) {
if (e.keyCode != 13) {
return false;
}
//Do Stuff
});
This code allows the user to either click the div or press the enter key. My problem, though, is that it really only allows the enter button due to the decision structure that filters the key code. How do I allow both the click and enter button event to go through?
jQuery events have a type property which you can check:
$(document).on('click keypress', '.pTile:not(.join)', function (e) {
if (e.type == 'keypress' && e.keyCode != 13) {
return false;
}
//Do Stuff
});
Alternatively you could extract the logic to its own function and add separate handlers:
function doStuff() {
// Do stuff...
}
$(document).on('click', '.pTile:not(.join)', doStuff);
$(document).on('keypress', '.pTile:not(.join)', function() {
if (e.keyCode == 13)
doStuff.call(this);
});

javascript prevent enterKey from adding new line

i am trying to submit the text in a textarea with the enterkey. thats working fine but the enterkey is always adding a new line before submitting the data...
i know that i have to use event.preventDefault() but it is not working for me.
ko.bindingHandlers.enterKey = {
init: function (element, valueAccessor, allBindingsAccessor, data) {
var wrappedHandler, newValueAccessor;
// wrap the handler with a check for the enter key
wrappedHandler = function (data, event) {
if (event.keyCode === ENTER_KEY && !event.shiftKey) {
event.target.blur();
valueAccessor().call(this, data, event);
}
};
// create a valueAccessor with the options that we would want to pass to the event binding
newValueAccessor = function () {
return {
keyup: wrappedHandler
};
};
// call the real event binding's init function
ko.bindingHandlers.event.init(element, newValueAccessor, allBindingsAccessor, data);
}
};
You should call event.preventDefault on keypress event.
For example, code below prevents enter key pressing
ko.bindingHandlers.enterKey = {
init: function (element, valueAccessor, allBindingsAccessor, data) {
$(element).keypress(function(e) {
(e.keyCode == 13) {
e.preventDefault();
// do something else
}
})
}
}

JAVASCRIPT - intercepting keycode 13 (enter) in dynamically-created editbox and passing element to different function

Ok..I've been working all day on a demo CRUD app learning some Bootstrap and JS basics...
I've almost got what I want but the last thing is I need it to do is while in the editbox to grab the keycode 13 event (enter) and so send the right class to a function that already works..
it all goes something like this...
$(function() {
...
...
$(document).on("blur", "input#editbox", function(){ saveEditable(this) });
});
function saveEditable(element) {
$('#indicator').show();
var User = new Object();
User.id = $('.current').attr('user_id');
User.field = $('.current').attr('field');
User.newvalue = $(element).val();
var userJson = JSON.stringify(User);
$.post('Controller.php',
{
action: 'update_field_data',
user: userJson
},
function(data, textStatus) {
$('td.current').html($(element).val());
$('.current').removeClass('current');
$('#indicator').hide();
},
"json"
);
}
function makeEditable(element) {
$(element).html('<input id="editbox" size="'+ $(element).text().length +'" type="text" value="'+ $(element).text() +'" onkeypress="return checkForEnter(event)">');
$('#editbox').focus();
$(element).addClass('current');
}
function checkForEnter(e){
if (e.keyCode == 13) {
saveEditable(e);
return false;
}
}
It works pretty good on the blur event firing but just isn't quite there for ENTER
here is the link...just Load the table and see http://markenriquez.tekcities.com/credapp
advTHNAKSance
You are passing event as argument to saveEditable() method from checkForEnter(). Wherein you should pass input field reference instead.
Try this,
function checkForEnter(e){
if (e.keyCode == 13) {
saveEditable(e.target);
return false;
}
}
Hope this helps.
$(window).on("keypress", "input#editbox",function(e){
if(e.keyCode == 13){
do_something();
}
});
PS. Your textarea top-left and bottom-left corners are rounded.

Bind any key (by keycode) to an action using Knockout

I'm looking for a method to bind many different keys to different actions/functions in my viewmodel.
I've found this example where a binding handler is used to bind actions to the enter-key.
But how do I modify this handler to also support a supplied key-code? I'd like to be able to use the same handler for all kinds of keys and preferably also combined with modifier keys.
ko.bindingHandlers.executeOnEnter = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var allBindings = allBindingsAccessor();
$(element).keypress(function (event) {
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 13) {
allBindings.executeOnEnter.call(viewModel);
return false;
}
return true;
});
}
};
You could do something like this:
ko.bindingHandlers.actionKey = {
init: function(element, valueAccessor, allBindings, data) {
var handler = function(data, event) {
var keys = ko.utils.unwrapObservable(allBindings().keys) || [13]; //default to Enter Key
if (!Array.isArray(keys))
keys = [keys];
if (keys.indexOf(event.keyCode) > -1) {
valueAccessor().call(data, data, event);
};
};
var newValueAccessor = function() {
return { keyup: handler };
};
ko.bindingHandlers.event.init(element, newValueAccessor, allBindings, data);
}
};
and you can use this binding in like this:
Observable Keys: <input data-bind="actionKey: action, keys: keyCodes" /><br/>
Inline Keys: <input data-bind="actionKey: action, keys: [33, 34]" /><br/>
Inline Key: <input data-bind="actionKey: action, keys: 33" /><br/>
Default Keys: <input data-bind="actionKey: action" /><br/>
Here is a fiddle demonstrating this binding.

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.
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
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.

Categories