jQuery - char counter doesn't work with paste event - javascript

I wrote a jQuery character counter, it works when I type, but not when text is pasted.
The function is executed upon paste, but count doesn't change. I am not sure if val() function is correct or really in synch with DOM. Any ideas?
counter = function () {
$j("strong#status-field-char-counter").text($j("#Panel1messagesmessage").val().length);
alert('event');
};
$j("textarea").keyup(counter);
$j("textarea").bind('paste', counter);
$j("#Panel1messagesmessage").bind('copy', counter);
$j("#Panel1messagesmessage").bind('delete', counter);

textarea contents can be changed in a number of ways, instead of trying to catch them all, simply install a routine that checks the content every 0.5 second, like
$(function() {
window.charCount = 0;
setInterval(function() {
var c = $("textarea").val().length;
if(c != window.charCount) {
window.charCount = c;
$("span").html(window.charCount);
}
}, 500);
})

I usually use keyup in combination with change
The change event fires when the textbox loses focus, but only if the value was modified since it received focus.

Quick play about:
$("#textarea").change(function() {
$("#status-field-char-counter").text($("#textarea").val().length);
}).keyup(function() {
$("#status-field-char-counter").text($("#textarea").val().length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<p id="status-field-char-counter">here</p>
<input id="textarea" type="text" />

Related

Jquery - check if control is NOT currently being edited

I have some code that updates controls on my page using Javascript/Ajax/Json calls.
My only problem is that sometimes the control is updated while the user is actively attempting to change the control.
For example - I will be typing in something, and the Ajax call will execute, replacing what I have typed.
Is this a way in javascript/jquery to say:
If $(this).NotBeingCurrentlyEdited ?
I know about the focus option, but how can I say "Not in focus, not being edited currently?"
You can use document.activeElement to check which element has the focus. If the element you want to change has the focus then skip the update. See example snippet below.
var val = 0;
setInterval(() => {
$('input').each((i, el) => {
if (document.activeElement !== el) {
$(el).val(val);
}
});
val++;
}, 2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="1">
<input id="2">
The way I would approach it is using a timer to determine if the textbox has recently been changed by the user. You could combine this with checking the control's focus as well once an Ajax request is received. You can either disregard updates to that field entirely when TextBoxIsBeingEdited = true or store the updates somewhere to push once the timer ticks.
var TextBoxIsBeingEdited = false;
function TextBoxEdited(){
if(TextBoxIsBeingEdited === false){
document.getElementById("TextBoxStatus").innerText = "Editing";
TextBoxIsBeingEdited = true;
setTimeout(ResetTextBoxEdited, 2000);
}
}
function ResetTextBoxEdited(){
document.getElementById("TextBoxStatus").innerText = "Not Being Edited";
TextBoxIsBeingEdited = false;
}
<input type="text" id="TextBox" oninput="TextBoxEdited()">
<br><br>
<div id="TextBoxStatus">
Not Being Edited
</div>

Jquery on keyup once

How to trigger another alert when I input some text on next time?
For example:
1. put some text
2. alert triggered
3. put some text again
4. alert trigger again
EDIT: I don't want to keep trigger the alert for every time i input, what i trying to do is... lets say I key in "abcd", the function should just trigger once. Then I click everywhere on the screen. Later, I key in "dddd" again in the textbox, the function trigger again for once
EDIT 2: Sry guys, maybe my requirement a bit confusing, i just edit the code and re-explain to illustrate my real case. So, first, i key in "abcd" on textbox, the tooltip should trigger once on first letter of "a". Then i click everywhere of the screen, the tooltip disappear. Next, I key in again "gfffee", the tooltip should appear again on first letter of "g".
<input type="text" id="test">
<input type="button" id="tool">
$('#test').one("keyup", function(){
$('#tool').tooltip("show");
});
$('#tool').tooltip({
placement: "bottom",
trigger: "focus",
title: "Click here",
});
ANSWER:
Thanks everyone for helping me, I managed solve it based on combination of everyone answer.
count = 0;
$('#test').on("change", function(){
count = 0;
});
$('#test').on("keyup", function(){
if(count == 0)
{
$('#tool').tooltip("show");
count = 1;
}
});
$('#tool').tooltip({
placement: "bottom",
trigger: "focus",
title: "Click here",
});
<input type="text" id="test">
<input type="button" id="tool">
Try this
var triggered = 0; // or false
$('#test').on('input', function() {
if(triggered == 0) {
alert('whatever message here');
triggered++;
}
});
$('#test').on('blur', function() {
// reset the triggered value to 0
triggered = 0;
});
I think there is no deterministic way to figure out when you are done with your input, using just the keyup event. But you can try debounce. I've added underscore.js to use debouce, but feel free to use your own implementation or another library. From the debounce docs of underscore
Useful for implementing behavior that should only happen after the input has stopped arriving
You can play around with the wait time to suit your needs. I've made it 500 ms
$('#test').on("keyup", _.debounce(function() {
alert("test");
}, 500));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<input type="text" id="test">
An excellent explanation of debounce here
Alternate solution
Another possible solution is to attach a blur handler, which will execute if clicked outside your input
$("#test").on("blur", function(e) {
alert("Test")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="test">
Can't you just use the onchange function? From your edit it seems like this would be more appropriate for your use case.
So
$('#test').on("change", function(){
alert("test");
});
on input clear the timer with clearTimeout(userTimer); then start new timer with setTimeout(doneType, maxTimer*1000); the maxTimer is in sec of your choose (2s here) if timeout call the function doneType
var userTimer;
var maxTimer = 2;
//on input, clear the timer and start new timer
$('#test').on('input', function () {
clearTimeout(userTimer);
userTimer = setTimeout(doneType, maxTimer*1000);
});
function doneType() {
alert('keep type?');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test">

How to define local variables in a jQuery .on function

I have an input HTML element and want to execute a function when there was an input and if this input didn't changed for 3 seconds.
Code:
$("#search_input").on('input', function() {
input_value = $("#search_input").val();
if (input_value != "") {
setTimeout(function() {
if (input_value == $("#search_input").val()) {
alert("still the same :) -> go search");
}
}, 3000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" id="search_input" placeholder="Search...">
The problem is that the handler refresh the input_value so it's always the same. How do you set the input_value as a local variable, so it's not refreshed?
You forgot the var declaration:
var input_value = $("#search_input").val();
while the var thing is true, it's unlikely the issue.
Looks like you want something like the link below, with the key difference being that you are setting a timeout and clearing the timeout as the input changes. By definition, the function above is always firing when input is changing so it's redundant.
Run javascript function when user finishes typing instead of on key up?
var var_name = value if it's a normal variable. Like a string or number.
Do $var_name = jQuery_object if it's a jQuery object.

jQuery, how to capture when text input has changed as a result of another event

I have a text input that is updated as a result of a button event. I would like to detect when the value in the text input has changed. See the example below:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#text').bind("input change paste", function(){
console.log("text changed");
// do something
});
$('#click').click (function(){
$('#text').val('something');
});
});
</script>
<body>
<input id='text' type='text'>
<input id='click' type='button' value='click'>
</body>
Later on, that button will trigger a calender so the user select a date/time which will update the text input. Since the calender is part of a library we I don't want to change it. I would like to detect when the text field gets a new value.
thanks!
I think what you're referring to is
$("#text").on("change", function(){});
take a look at this post
Since the date/time picker library you are using doesn't raise any sort of change or input event, the only way to reliable tell if the value has changed is to watch with a timer and raise the change event yourself. The following is one way to do this:
// check for changes every 100 ms
setInterval(function() {
var lastVal = $('#text').data('last-value');
if (typeof lastVal === 'undefined') {
lastVal = $('#text').val();
$('#text').data('last-value', lastVal);
}
if (lastVal !== $('#text').val()) {
$('#text').change(); // trigger the change event
}
}, 100);
// setup your change handler
$('#text').on("input change paste", function() {
// before doing anything else, set the last-value data property
$('#text').data('last-value', $('#text').val());
// do something ...
console.log('changed!');
});
// now programmitically updating the $('#text') element will result
// in your change handler being triggered
$('#click').click (function(){
$('#text').val('something');
});

Detect Textbox Field Change jQuery

I have a text box that accepts integers, and I need it to run a function that will use the text box's input, as soon as a user inputs numbers into the field.
The problem here is that keyUp() will detect each and every input. So if I type 23, it will fire once for 2 and once for 3. I only need it to run when the input is complete.
Is there a way to do this, without losing focus and without using a timer that will keep checking the text box input every while using setInterval?
Look like you want to be notified when the user stops typing. The following code can be used as a starting point, it calls bufferedKeyUp 300 ms after the user stops typing. http://jsfiddle.net/mendesjuan/VTMEe/
$(function() {
// Creates a handler that will wait until the event hasn't fired for a period
// before it fires the actual event handler
function createBuffered(fun, delay) {
var timer;
return function() {
clearTimeout(timer);
var args = arguments;
var me = this;
timer = setTimeout(function() {
fun.apply(me, args);
}, delay);
}
}
$('#in').keyup( createBuffered(function(){
console.log('change');
}, 300));
});​
Ext-JS has a nice simple way to do this http://jsfiddle.net/mendesjuan/DYkmU/1/
Ext.get('myid').on('keyup', function() {
console.log('change');
}, null, {buffer: 300});
Why not test the textbox contents after they're changed, after all that's when input is complete isn't it?
If the result is not okay, you can always clear and focus the textbox so the user has to enter valid data.
Something like:
$("textbox").change( function () {
if (someTestForGoodData) {
handleTheGoodData();
} else {
$(this).focus();
alert($(this) + " has bad data!");
}
})
$('input').on('input propertychange', function() {
$('#output').html($(this).val().length + ' characters');
});
From this answer.

Categories

Resources