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
}
})
}
}
Related
I have a fiddle here: https://jsfiddle.net/419r62t8/1/
View.prototype.render = function (viewCmd, parameter) {
var that = this;
var viewCommands = {
showEntries: function () {
that.$todoList.innerHTML = that.template.show(parameter);
},
removeItem: function () {
that._removeItem(parameter);
},
updateElementCount: function () {
that.$todoItemCounter.innerHTML = that.template.itemCounter(parameter);
},
contentBlockVisibility: function () {
that.$main.style.display = that.$footer.style.display = parameter.visible ? 'block' : 'none';
},
setFilter: function () {
that._setFilter(parameter);
},
clearNewTodo: function () {
that.$newTodo.value = '';
},
editItem: function () {
that._editItem(parameter.id, parameter.title);
},
editItemDone: function () {
that._editItemDone(parameter.id, parameter.title);
}
};
viewCommands[viewCmd]();
};
View.prototype._itemId = function (element) {
var li = $parent(element, 'li');
return parseInt(li.dataset.id, 10);
};
View.prototype._bindItemEditDone = function (handler) {
var that = this;
$live('#todo-list li .edit', 'blur', function () {
if (!this.dataset.iscanceled) {
handler({
id: that._itemId(this),
title: this.value
});
}
});
$live('#todo-list li .edit', 'keypress', function (event) {
if (event.keyCode === that.ENTER_KEY) {
// Remove the cursor from the input when you hit enter just like if it
// were a real form
this.blur();
}
});
};
View.prototype._bindItemEditCancel = function (handler) {
var that = this;
$live('#todo-list li .edit', 'keyup', function (event) {
if (event.keyCode === that.ESCAPE_KEY) {
this.dataset.iscanceled = true;
this.blur();
handler({id: that._itemId(this)});
}
});
};
View.prototype.bind = function (event, handler) {
var that = this;
if (event === 'newTodo') {
$on(that.$newTodo, 'change', function () {
handler(that.$newTodo.value);
});
} else if (event === 'itemEdit') {
$live('#todo-list li label', 'dblclick', function () {
handler({id: that._itemId(this)});
});
} else if (event === 'itemRemove') {
$live('#todo-list .destroy', 'click', function () {
handler({id: that._itemId(this)});
});
} else if (event === 'itemEditDone') {
that._bindItemEditDone(handler);
} else if (event === 'itemEditCancel') {
that._bindItemEditCancel(handler);
} else if (even === 'itemComplete') {
that._bindItemComplete(handler);
}
};
EDIT: I am thinking I can bind a new function here to add an strike-through to the "completed" items on the todo list. Completing them on single click or by adding a checkbox for completing it.
I've got the CSS but I'm lacking the JS to tie it all together.
I am attempting to create a simple strike through on-click to show when an item has been marked as completed. Any help would be much appreciated.
You're close with the CSS, but the best bet is to replace the checkbox with an image (svg if you can) when it is checked.
text-decoration: line-through will not help here -- this only works with text.
Often the checkbox's label will get the image and the checkbox itself will be hidden (a label can be clicked and perform the same actions as the input/checkbox itself)
Check this Answer out and see if it'll help you along your path:
Pure CSS Checkbox Image replacement
Try adding a jquery event listener to the id of the checkbox. Tell id to toggle the css on click and you should be good to go. Do you know how to achieve that?
I have a enrollment form with some customer related information. If user form is half filled and the user is going to close the tab, then I'll trigger the popup with option of save and exit, exit.
I have some jQuery solution. But nowadays it's not working in all browsers.
Jquery sample Code:
'use strict';
$(document).ready(function() {
$.fn.addEvent = function (obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent('on'+evType, fn);
return r;
} else {
return false;
}
};
$.fn.KeepOnPage = function (e) {
var doWarn = 1;
if (!e) {
e = window.event;
}
if (!e) {
return;
}
if (doWarn == 1) { // and condition whatever you want to add here
e.cancelBubble = true;
e.returnValue = 'Warning!\n\nNavigating away from this page will delete your text if you haven\'t already saved it.';
}
if (e.stopPropagation) {
e.stopPropagation();
}
};
$.fn.addEvent(window, 'beforeunload', $.fn.KeepOnPage);
});
But we need solution in ReactJS. Is there any React library for the browser unload?
Thanks,
Thangadurai
You can add and remove an event listener for the 'beforeunload' event within your componentDidMount and componentWillUnmount lifecycle functions.
https://facebook.github.io/react/docs/component-specs.html
https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
Example:
...
componentDidMount() {
window.addEventListener('beforeunload', this.keepOnPage);
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.keepOnPage);
}
keepOnPage(e) {
var message = 'Warning!\n\nNavigating away from this page will delete your text if you haven\'t already saved it.';
e.returnValue = message;
return message;
}
....
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/
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.
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.