jQuery keyup only keys that affects textarea content - javascript

How can I detect if the value of a textarea changes using jQuery? I'm currently using keyup() but this triggers every key stroke of course, I dont want my code to run if it's an arrow key that was pressed or any other key that doesn't have an impact on the value of the textarea.
Take a look:
$('textarea').keyup(function() {
if (content was changed)
// Do something
});
I hope you understand. How can I do this the best way? I don't want to compare the current value to an old value to check for changes, I hope that's not the only way.

By all means the easiest way is to store old values to data and do the check every keyup. The solution is quite short and will work in any case. No need to reinvent the wheel.
$("textarea").data("oldValue", function() {
return this.value;
}).keyup(function() {
var $this = $(this);
if (this.value !== $this.data("oldValue")) {
// Do something
$this.data("oldValue", this.value);
}
});
DEMO: http://jsfiddle.net/vvbSj/

$('textarea').blur(function() {
//This will be invoked when the focus is removed
});
$('textarea').change(function() {
//Same as the blur
});
Is this what you want

Related

Find what specific part of the form has changed on input

I have multiple forms on my page with the following function:
$('#pageContainer').on('input propertychange change', '#form1', function() {}
Within this function, I make 11 function calls that formats text for 11 different textarea box's. I don't need to call all 11, just the one's that have changed that need formatting.
Is there a way to figure out what part of the form has been changed that made the function call so that I can call the correct (1 of 11) functions, or none at all?
So basically, if textarea 1-11 has been the input that calls the .on(), call that specific function. If not, don't call anything.
You can use event.target to find out which element caused the change event.
$('#pageContainer').on('input propertychange change', '#form1', function(e) {
var elementId = e.target.id;
//Do you actions based on this
}
I don't think there's a nice handy function to check these things, but you could assign an event handler on the onChange event, this could add $(this).attr("id") to an array. You could then construct a selector based on that array?
for example
var changes = [];
$("input").on('change', function() {
changes.push($(this).attr(id));
});
function yourFormattingFunction() {
var selector = "#" + changes.splice(", #");
$(selector).each(function() {
//...Do your formatting here
});
}
Obvious improvements like making sure the list is unique etc can be done to improve this...

Input value onkeydown returns incorrect value (one less)

I'm working on a script for our client's project that autotabs you onto the next input field when you've hit the maximum character count for a particular input. For some reason the input value is returning one less than it should be, and therefore tabs to the 'next' input when an extra character is entered above the 'threshold'.
Here's my script to watch the inputs value - ofc, if there is a better way please advise :) -
var watchLength = function (watch) {
watch.onkeypress = function () {
var nextInput = getNextSibling(this);
console.log(this.getAttribute('data-autotab-length'));
console.log(this.value.length);
if (this.value.length == this.getAttribute('data-autotab-length')) {
nextInput.focus();
console.log('Limit reached here');
}
};
};
And a jsFiddle to the working input. The first input is limited to '2' characters, but when you type in 3 it jumps to the next input. I think this is something to do with the keypress/keydown event not reading the initial value, but I'm at a loss of how to fix it. Any help really appreciated.
I'm logging the results in the Console:
http://jsfiddle.net/qdnCZ/
The Problem is, that onkeypress will fire before you want it to. You can simply replace onkeypress by onkeyup, that way you make sure that the <input> elements value is set correctly the time you check it.
See: http://jsfiddle.net/qdnCZ/1/
Yes it will return one less, simply use +1 on the length check. This is beacuse onkeypress event is executed before the field is updated, which means using e.preventDefault() the letter will not appear in the field. You could use onkeyup otherwise.
Use onkeyup instead onkeypress
onkeyup gets fired after field gets updated
if (this.value.length == this.getAttribute('data-autotab-length')) {
nextInput.focus();
console.log('Limit reached here');
return false; // this is prevent the third value being entered
}
Updated fiddle

javascript - modifying text entered into TextBox

I would like to catch an event that some text was entered to a TextBox and modify it BEFORE user sees the change.
I tried adding the keyDown, keyUp and keyPressed events, but they are all called after the change.
Is there a way to do that?
This has to work
$("#input").keypress(function(replace){
if(replace.which==46)
{
$("#input").val($(this).val() + 'no_dots');
replace.preventDefault();
}
});
It replaces (,) characters, try this code I think it keypress works well
This seems to be what you're after. http://jsfiddle.net/wcS9j/1/
var blacklist = /(foo|bar)/ig;
$('input').on('keyup', function () {
if (blacklist.test(this.value)) {
this.value = this.value.replace(blacklist, '');
}
});

Printing field input data live with Javascript

Got a question for you javascript gurus out there. I'm creating a sidebar tool that is comprised of a few different text input fields. The purpose of this tool is to edit copy on a template. I've tried to pass the data entered into the field onchange, but I'm running into problems dumping the data into my js object. This is somewhat what I have in mind:
$('myInputField').(function(){
$(this).onChange(){
// write to variable X
}
});
Essentially I want to have what I'm typing in the input be mimicked live and then I can parse the changes to my database.
$('#myInputField').(function(){
$(this).onkeyup(){
x = this.value;
}
});
or more succinctly:
$('#myInputField').onkeyup(){
x = this.value;
});
You're just looking for the value that's in myInputField within that event handler? Something like this?:
$('myInputField').(function(){
$(this).onChange(){
x = $(this).val();
}
});
I don't remember off the top of my head if this is already a jQuery object. If it is, then this should work and perhaps skip a little bit of overhead:
x = this.val();
Additionally, you can explicitly reference the field with a normal jQuery selector if this is ever overridden with a different context, or if you want to reference other fields as well, etc.:
x = $('myInputField').val();
The problem is, on IE, the onchange event doesn't work on INPUT elements. Thus, you have to use the onkeypress or the onblur event depending on what you want to do.
JS way:
document.getElementById('myInputField').onblur = function() {
var x = this.value
}
jQuery way:
$('#myInputField').blur(function() {
var x = this.value
})
Wouldn't a simply keyup event on the input fields be sufficient?
jQuery:
$('textarea').keyup(function() {
$('#foo').html($(this).val());
});​
HTML:
<textarea></textarea>
<div id="foo"></div>
jsFiddle example.

Jquery text change event

I need to fire an event anytime the content of a textbox has changed.
I cant use keyup nor can I use keypress.
Keyup and keydown doesn't work if you hold down on the key.
Keypress triggers before the text has actually changed. It doesn't recognize backspace or delete either.
So now I'm assuming I'm going to have to build some custom logic or download a plugin. Are there any plugins out there? Or if I should build one, what constraints should I look out for?
For eg. Facebook does it with their search at the top. you can press and hold.
another example is writing a stackoverflow question. Right below the editor, the contents are copied in real time, backspace and everythng works. How do they do it?
I just took a look at SO's source. It looks like they do something a lot like this:
function updatePreview(){
$('div').text($('textarea').val());
}
$('textarea').bind('keypress', function(){
setTimeout(updatePreview, 1);
}
);​
They do some extra stuff to make HTML tags for bold and italics and links and such and they time it. They increase the delay from 1 to longer if it takes too long to generate the HTML.
I had success using jQuery (in Chrome). If you hold a key down, it counts every change, not just the first one, and it counts non-print keys like backspace.
HTML
<input id="txt" type="text" />
<span id="changeCount">0</span>
JavaScript
$('#txt').keydown(function(event) {
// Don't count the keys which don't actually change
// the text. The four below are the arrow keys, but
// there are more that I omitted for brevity.
if (event.which != 37 && event.which != 38 &&
event.which != 39 && event.which != 40) {
// Replace the two lines below with whatever you want to
// do when the text changes.
var count = parseInt($('#changeCount').text(), 10) + 1;
$('#changeCount').text(count);
}
});
Like I said above, you'll want to filter out all of the key codes that don't change the text, like ctrl, shift, alt, enter, etc. There's also the boundary condition if you press the backspace or delete key when the textbox is empty or if the textbox has a maximum length and a printable key is pressed, but it's not terribly difficult to handle those either.
Here's a working jsfiddle example.
How about a poll? Do a setInterval and call a function that checks the text say every 500ms? You don't want to detect content change on every key anyway because it gets kinda slow in some older browser/older computer and you would notice a lag between typing and the text displaying.
You need a watcher type functionality.
It resorts to setInterval polling if the other features are not available: http://james.padolsey.com/javascript/monitoring-dom-properties/
I have a simple solution that we use happily in one of our project.
you can try it # http://jsfiddle.net/zSFdp/17/
var i = 0;
$('#text').bind('check_changed', function(){
var t = $(this);
// do something after certain interval, for better performance
delayRun('my_text', function(){
var pv = t.data('prev_val');
// if previous value is undefined or not equals to the current value then blablabla
if(pv == undefined || pv != t.val()){
$('#count').html(++i);
t.data('prev_val', t.val());
}
}, 1000);
})
// if the textbox is changed via typing
.keydown(function(){$(this).trigger('check_changed')})
// if the textbox is changed via 'paste' action from mouse context menu
.bind('paste', function(){$(this).trigger('check_changed')});
// clicking the flush button can force all pending functions to be run immediately
// e.g., if you want to submit the form, all delayed functions or validations should be called before submitting.
// delayRun.flush() is the method for this purpose
$('#flush').click(function(){ delayRun.flush(); });
The delayRun() function
;(function(g){
var delayRuns = {};
var allFuncs = {};
g.delayRun = function(id, func, delay){
if(delay == undefined) delay = 200;
if(delayRuns[id] != null){
clearTimeout(delayRuns[id]);
delete delayRuns[id];
delete allFuncs[id];
}
allFuncs[id] = func;
delayRuns[id] = setTimeout(function(){
func();
delete allFuncs[id];
delete delayRuns[id];
}, delay);
};
g.delayRun.flush = function(){
for(var i in delayRuns){
if(delayRuns.hasOwnProperty(i)){
clearTimeout(delayRuns[i]);
allFuncs[i]();
delete delayRuns[i];
delete allFuncs[i];
}
}
};
})(window);
Zurb has a great plugin which might be useful for you
http://www.zurb.com/playground/jquery-text-change-custom-event

Categories