Jquery on keyup once - javascript

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

Related

Detect changes made to input through code

Somewhere in my page I have an button that when clicked changes the value of another input. However I don't have control over the code where the click event is defined (on a clients' CDN) and I didn't bother to look. I just want to capture the event when my inputs' value is change through the code. Here's an example:
HTML
<input type="text" id="myinput" />
<input type="button" id="theonechanging" value="Click Me" />
<br />
<p id="message"></p>
JS
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + i++);
});
$("#myinput").on("input change bind",function(e) {
$("#message").text("changed " + i++);
});
Here's a fiddle where you can test the situation: http://jsfiddle.net/fourat05/t9x6uhoh/
Thank you for your help !
There's an incredibly hacky way to do this.
What you do is replace the jQuery.fn.val function with your own implementation, and call the old implementation from the new one. This technique is a kind of Monkey patching.
The implementation is as follows:
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + ++i);
});
var handleChanges = function(){
$("#message").text("changed " + i);
}
var oldval = jQuery.fn.val;
jQuery.fn.val = function(){
oldval.apply(this,arguments);
if(this.attr('id') === 'myinput'){ //and possibly add a check for changes
handleChanges();
}
}
$("#myinput").on("input change bind",function(e) {
i++;
handleChanges();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="myinput" />
<input type="button" id="theonechanging" value="Click Me" />
<br />
<p id="message"></p>
However, I strongly recommend against using it, because:
This alters the behaviour of a widespread library, thus creating possible pitfalls for the developers producing code for the same page
It will quickly become complicated to detect multiple events on multiple elements.
Please understand the side effects of this method before implementing it.
Values changed directly in the DOM dont trigger those events, but since you have an action that is called to change the value, you can trigger the input change event.
$("#theonechanging").on("click", function(e) {
$("#myinput").trigger("change");
});
fiddle
use triggers
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + i++);
});
$("#theonechanging").on("click", function(e) {
$("#myinput").trigger("change");
});
$("#myinput").on("input change bind",function(e) {
$("#message").text($("#myinput").val());
});
Fiddle
I think it is not possible without changing the script for BUTTON.
When the user click the 'Button', you should trigger another function to catch the change in 'Input'.
If you don't want to change the 'Button' script, you can try something like the code below, seeking for the correct combination of events:
(check the list of events here: http://www.w3schools.com/tags/ref_eventattributes.asp)
<html>
<body>
<input type="text" id="myinput" onchange="change_Message('onchange')"
onclick="change_Message('onclick')"
oninput="change_Message('oninput')"
onkeypress="change_Message('onkeypress')"/>
<input type="button" id="theonechanging" value="Click Me" onclick="change_Input()"/>
<br />
<p id="message"></p>
<script>
var input_value = document.getElementById('myinput').value; // as global variable
function Test_if_Change()
{
if ( document.getElementById('myinput').value != input_value )
{
change_Message('Test_if_Change');
}
}
setInterval(Test_if_Changed, 10);
function change_Input() { document.getElementById('myinput').value = 'input changed by button'; }
function change_Message(event) { document.getElementById('message').innerHTML = 'message changed by '+event+' to: ' + document.getElementById('myinput').value; }
</script>
</body>
</html>
There is no perfect way to detect input value changes through code but if you you are using jquery ,you can hook the val function and trigger change event manually.
jQuery.fn._val = jQuery.fn.val;
jQuery.fn.val = function(){
jQuery.fn._val.apply(this,arguments);
if(arguments.lenght==1){
this.trigger('code-change');
}
}
}

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');
});

Making JavaScript not work when clicked for the second time

I have this code:
<form method="get" >
<input type="text" name="keyword" id="map">
<img src="style/keyboard.png" id="click"/>
<button type="submit">Search</button>
</form>
And this javascript thing, adopted from here, whose job is showing the virtual keyboard when the img is clicked:
$('‪#‎map‬').keyboard({
layout: 'custom',
customLayout: {
'default': [
'\u0192(h):lower_case_function_(type_h) \n\
\u0393(h):lower_case_gamma_(type_h) \n\
\u0394(h):lower_case_delta_(type_h)\n\
',
'{shift} {accept} {cancel}'
],
'shift': [
'\u03C6(h):lower_case_phi_(type_h) \n\
\u03C7(h):lower_case_chi_(type_h) \n\
\u03C8(h):lower_case_psi_(type_h) \n\
',
'{shift} {accept} {cancel}'
]
},
usePreview: false,
openOn:null
})
.addTyping();
$('‪#‎click‬').click(function() {
$('#map').getkeyboard().reveal();
});
They work fine.
But,
The problem is when the img is clicked for the second time, it doesn't hide the virtual keyboard. What I want is when the img is clicked, the keyboard appears. When it's clicked again (twice), the keyboard disappears. When it's clicked for the third time, the keyboard reappears.
How do I do that?
I've googled for this issue and still have no idea what to do.
Thanks..
EDITED:
*Solved by using answer from #Arjun Vachhani*
$("#click").toggle(
function()
{
$('#map').getkeyboard().reveal();
},
function() {
$('#map').getkeyboard().close();
});
you can use jquery toggle
$("#id").toggle(
function ()
{
alert("action 1");
},
function () {
alert("action 2");
});
just paste code in first function that should handle the odd number of click event
and paste code in second function that handles even number of clicks
it will work
If the HTML is changing after the first click, this won't work at second time:
$('‪#‎click‬').click(function() {...
Try to use jquery .on(), beacuse the click works when the element is in DOM.
add an Id to your form:
$("‪form#myform‬").on("click","img#‎click",function() {...
or just:
$("‪form").on("click","img#‎click",function() {...
Jquery .on()
First time triggers both, but second time only the .on() works.
Jsfiddle

jQuery - char counter doesn't work with paste event

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" />

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

What is a Vanilla JS or jQuery solution that will select all of the contents of a textbox when the textbox receives focus?
$(document).ready(function() {
$("input:text").focus(function() { $(this).select(); } );
});
<input type="text" onfocus="this.select();" onmouseup="return false;" value="test" />
$(document).ready(function() {
$("input[type=text]").focus().select();
});
$(document).ready(function() {
$("input:text")
.focus(function () { $(this).select(); } )
.mouseup(function (e) {e.preventDefault(); });
});
jQuery is not JavaScript which is more easy to use in some cases.
Look at this example:
<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>
Source: CSS Tricks, MDN
This is not just a Chrome/Safari issue, I experienced a quite similar behavior with Firefox 18.0.1. The funny part is that this does not happen on MSIE! The problem here is the first mouseup event that forces to unselect the input content, so just ignore the first occurence.
$(':text').focus(function(){
$(this).one('mouseup', function(event){
event.preventDefault();
}).select();
});
The timeOut approach causes a strange behavior, and blocking every mouseup event you can not remove the selection clicking again on the input element.
HTML :
var textFiled = document.getElementById("text-filed");
textFiled.addEventListener("focus", function() { this.select(); });
Enter Your Text : <input type="text" id="text-filed" value="test with filed text">
Using JQuery :
$("#text-filed").focus(function() { $(this).select(); } );
Using React JS :
In the respective component -
<input
type="text"
value="test"
onFocus={e => e.target.select()}
/>
my solution is to use a timeout. Seems to work ok
$('input[type=text]').focus(function() {
var _this = this;
setTimeout(function() {
_this.select();
}, 10);
});
This will also work on iOS:
<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
I know inline code is bad style, but I didn't want to put this into a .js file.
Works without jQuery!
<input type="text" value="blah blah" onfocus="this.select(); this.selAll=1;" onmouseup="if(this.selAll==0) return true; this.selAll=0; return false;"></input>
The answers here helped me up to a point, but I had a problem on HTML5 Number input fields when clicking the up/down buttons in Chrome.
If you click one of the buttons, and left the mouse over the button the number would keep changing as if you were holding the mouse button because the mouseup was being thrown away.
I solved this by removing the mouseup handler as soon as it had been triggered as below:
$("input:number").focus(function () {
var $elem = $(this);
$elem.select().mouseup(function (e) {
e.preventDefault();
$elem.unbind(e.type);
});
});
Hope this helps people in the future...
This will work, Try this -
<input id="textField1" onfocus="this.select()" onmouseup="return false" />
Works in Safari/IE 9 and Chrome, I did not get a chance to test in Firefox though.
I know there are already a lot of answers here - but this one is missing so far; a solution which also works with ajax generated content:
$(function (){
$(document).on("focus", "input:text", function() {
$(this).select();
});
});
Like #Travis and #Mari, I wanted to autoselect when the user clicked in, which means preventing the default behaviour of a mouseup event, but not prevent the user from clicking around. The solution I came up with, which works in IE11, Chrome 45, Opera 32 and Firefox 29 (these are the browsers I currently have installed), is based on the sequence of events involved in a mouse click.
When you click on a text input that does not have focus, you get these events (among others):
mousedown: In response to your click. Default handling raises focus if necessary and sets selection start.
focus: As part of the default handling of mousedown.
mouseup: The completion of your click, whose default handling will set the selection end.
When you click on a text input that already has focus, the focus event is skipped. As #Travis and #Mari both astutely noticed, the default handling of mouseup needs to be prevented only if the focus event occurs. However, as there is no "focus didn't happen" event, we need to infer this, which we can do within the mousedown handler.
#Mari's solution requires that jQuery be imported, which I want to avoid. #Travis's solution does this by inspecting document.activeElement. I don't know why exactly his solution doesn't work across browsers, but there is another way to track whether the text input has focus: simply follow its focus and blur events.
Here is the code that works for me:
function MakeTextBoxAutoSelect(input)
{
var blockMouseUp = false;
var inputFocused = false;
input.onfocus =
function ()
{
try
{
input.selectionStart = 0;
input.selectionEnd = input.value.length;
}
catch (error)
{
input.select();
}
inputFocused = true;
};
input.onblur =
function ()
{
inputFocused = false;
};
input.onmousedown =
function ()
{
blockMouseUp = !inputFocused;
};
input.onmouseup =
function ()
{
if (blockMouseUp)
return false;
};
}
I hope this is of help to someone. :-)
I was able to slightly improve Zach's answer by incorporating a few function calls. The problem with that answer is that it disables onMouseUp completely, thereby preventing you from clicking around in the textbox once it has focus.
Here is my code:
<input type="text" onfocus="this.select()" onMouseUp="javascript:TextBoxMouseUp();" onMouseDown="javascript:TextBoxMouseDown();" />
<script type="text/javascript">
var doMouseUp = true;
function TextBoxMouseDown() {
doMouseUp = this == document.activeElement;
return doMouseUp;
}
function TextBoxMouseUp() {
if (doMouseUp)
{ return true; }
else {
doMouseUp = true;
return false;
}
}
</script>
This is a slight improvement over Zach's answer. It works perfectly in IE, doesn't work at all in Chrome, and works with alternating success in FireFox (literally every other time). If someone has an idea of how to make it work reliably in FF or Chrome, please share.
Anyway, I figured I'd share what I could to make this a little nicer.
What is a JavaScript or jQuery solution that will select all of the contents of a textbox when the textbox receives focus?
You only need to add the following attribute:
onfocus="this.select()"
For example:
<input type="text" value="sometext" onfocus="this.select()">
(Honestly I have no clue why you would need anything else.)
This worked for me (posting since it is not in answers but in a comment)
$("#textBox").focus().select();
onclick="this.focus();this.select()"
$('input').focus(function () {
var self = $(this);
setTimeout(function () {
self.select();
}, 1);
});
Edit: Per #DavidG's request, I can't provide details because I'm not sure why this works, but I believe it has something to do with the focus event propagating up or down or whatever it does and the input element getting the notification it's received focus. Setting the timeout gives the element a moment to realize it's done so.
If you chain the events together I believe it eliminates the need to use .one as suggested elsewhere in this thread.
Example:
$('input.your_element').focus( function () {
$(this).select().mouseup( function (e) {
e.preventDefault();
});
});
Note: If you are programming in ASP.NET, you can run the script using ScriptManager.RegisterStartupScript in C#:
ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );
Or just type the script in the HTML page suggested in the other answers.
I sow this one some where , work perfectly !
$('input').on('focus', function (e) {
$(this)
$(element).one('mouseup', function () {
$(this).select();
return false;
}) .select();
});
I'm kind of late to the party, but this works perfectly in IE11, Chrome, Firefox, without messing up mouseup (and without JQuery).
inputElement.addEventListener("focus", function (e) {
var target = e.currentTarget;
if (target) {
target.select();
target.addEventListener("mouseup", function _tempoMouseUp(event) {
event.preventDefault();
target.removeEventListener("mouseup", _tempoMouseUp);
});
}
});
My solution is next:
var mouseUp;
$(document).ready(function() {
$(inputSelector).focus(function() {
this.select();
})
.mousedown(function () {
if ($(this).is(":focus")) {
mouseUp = true;
}
else {
mouseUp = false;
}
})
.mouseup(function () {
return mouseUp;
});
});
So mouseup will work usually, but will not make unselect after getting focus by input

Categories

Resources