I'm having a little problem with my script below. I'm trying to create a script where you can write some text in an input field, and when you have typed some text, you will get an alert when focus-out. The alert should only show, if the input contain text.
But the problem is, that if you're trying to write some text, delete it and then focus-out of the input, the alert do not show next time, when you actually have written something and then focus-out.
Right now, the alert function always will "disappear" when focus out, no matter if you have written any thing or not.
I have tried to add a var already_alert_me_once = true before the alert, and then put everything inside an: if(already_alert_me_once == false), but that didn't do the trick.
I have also tried to change $('#title').focusout(function() with $('#title').one('focusout', function() which almost did the trick.
Here is my current script:
// When focus on title
$('#title').focus(function () {
// Check if empty
if (!$(this).val()) {
$('#title').one('focusout', function () {
if ($(this).val()) {
alert("YEP");
}
});
}
});
..and Here's a Fiddle
So my question is; How to I do so the alert only appears when you have written something, and after that never again (unless you reload the page).
Hope you can understand what I mean.
Thanks - TheYaXxE
You can unbind the focus using:
$('#title').unbind('focus');
Working Fiddle
pretty much the easiest solution, no need for .one or focus events :)
$('#title').blur(function() {
if( $(this).val() ) {
alert('!!');
$(this).unbind('blur');
}
});
http://jsfiddle.net/T7tFd/5/
instead of putting the variable "already_alert_me_once" inside the function, make it a global variable. that way the scope will be maintained. you could also add an attribute to the #title that indicates that it has already been clicked, then check to see if that attribute exists before executing the code.
Related
I have a webpage with a small survey. I want to pre populate some of the answers based on user inputs to previous question.
In the below code, if value of id QR~QID3 depends upon value of QID1_Total. However after the page loaded and even if the condition is met the textbox is not populated with correct value.
.addOnload(function()
{
if(document.getElementById("QID1_Total").value>15) {
document.getElementById("QR~QID3").value = "Good";
}
else{
document.getElementById("QR~QID3").value = "Average";
}
});
$("#QID1_Total").on("input", function() {
//statements goes here
});
use of on("input" will track every inputting event, include drop and paste.
know more about onInput : https://mathiasbynens.be/notes/oninput
Here is an Fiddle Example to know how trigger works :
https://jsfiddle.net/5sotpa63/
An Assumption
Let Us Say you are using a function, which holds this statement show Good and Average according to users Input.
var targetElem = document.getElementById("QID1_Total");
var showComment = (targetElem,value>15) ? "Good" : "Average";
document.getElementById("QR~QID3").value = showComment;
Above code is the shorter method of your own statement mentioned in your question.
Now on Change of the target QR~QID3 you need to load some content. you utilize the below code as follows.
$("#QR~QID3").on("input", function() {
//your next question loading statements goes here,
//statements to proceed when you show some comment Good or Average
}).trigger("input");
Hope! this could be helpful.
$('#QID1_Total').keydown(function () {
//ur code
});
as the mouse key is pressed in the input field the function is called
You need to add an event listener to the "QID1_Total" element.
If you want to run the check while the user changes the input, i.e. after each keypress use the oninput event.
If you want to run the check after the user has completed the input, use the onchange event. The onchange event will only fire after the input loses focus.
You can bind the event listeners by using the addEventListener() function like this:
document.getElementById("QID1_Total").addEventListener("input", function(){
//Code goes here
});
Here is a JSFiddle showing both methods.
You also have to use the parseInt() function on the textbox values before you can perform mathematical functions with them.
I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the keyup, change and click events.
The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither change nor click). Note that if you select from the autocomplete box and the blur the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .
See: http://jsfiddle.net/pYKKp/ (hopefully you have filled out a lot of forms in the past with an input named "email").
HTML:
<input name="email" />
<div id="whatever"><whatever></div>
CSS:
div {
float: right;
}
Script:
$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
I recommending using monitorEvents. It's a function provide by the javascript console in both web inspector and firebug that prints out all events that are generated by an element. Here's an example of how you'd use it:
monitorEvents($("input")[0]);
In your case, both Firefox and Opera generate an input event when the user selects an item from the autocomplete drop down. In IE7-8 a change event is produced after the user changes focus. The latest Chrome does generate a similar event.
A detailed browser compatibility chart can be found here:
https://developer.mozilla.org/en-US/docs/Web/Events/input
Here is an awesome solution.
$('html').bind('input', function() {
alert('test');
});
I tested with Chrome and Firefox and it will also work for other browsers.
I have tried a lot of events with many elements but only this is triggered when you select from autocomplete.
Hope it will save some one's time.
Add "blur". works in all browsers!
$("input").on('blur keyup change click', function () {
As Xavi explained, there's no a solution 100% cross-browser for that, so I created a trick on my own for that (5 steps to go on):
1. I need a couple of new arrays:
window.timeouts = new Array();
window.memo_values = new Array();
2. on focus on the input text I want to trigger (in your case "email", in my example "name") I set an Interval, for example using jQuery (not needed thought):
jQuery('#name').focus(function ()
{
var id = jQuery(this).attr('id');
window.timeouts[id] = setInterval('onChangeValue.call(document.getElementById("'+ id +'"), doSomething)', 500);
});
3. on blur I remove the interval: (always using jQuery not needed thought), and I verify if the value changed
jQuery('#name').blur(function ()
{
var id = jQuery(this).attr('id');
onChangeValue.call(document.getElementById(id), doSomething);
clearInterval(window.timeouts[id]);
delete window.timeouts[id];
});
4. Now, the main function which check changes is the following
function onChangeValue(callback)
{
if (window.memo_values[this.id] != this.value)
{
window.memo_values[this.id] = this.value;
if (callback instanceof Function)
{
callback.call(this);
}
else
{
eval( callback );
}
}
}
Important note: you can use "this" inside the above function, referring to your triggered input HTML element. An id must be specified in order to that function to work, and you can pass a function, or a function name or a string of command as a callback.
5. Finally you can do something when the input value is changed, even when a value is selected from a autocomplete dropdown list
function doSomething()
{
alert('got you! '+this.value);
}
Important note: again you use "this" inside the above function referring to the your triggered input HTML element.
WORKING FIDDLE!!!
I know it sounds complicated, but it isn't.
I prepared a working fiddle for you, the input to change is named "name" so if you ever entered your name in an online form you might have an autocomplete dropdown list of your browser to test.
Detecting autocomplete on form input with jQuery OR JAVASCRIPT
Using: Event input. To select (input or textarea) value suggestions
FOR EXAMPLE FOR JQUERY:
$(input).on('input', function() {
alert("Number selected ");
});
FOR EXAMPLE FOR JAVASCRIPT:
<input type="text" onInput="affiche(document.getElementById('something').text)" name="Somthing" />
This start ajax query ...
The only sure way is to use an interval.
Luca's answer is too complicated for me, so I created my own short version which hopefully will help someone (maybe even me from the future):
$input.on( 'focus', function(){
var intervalDuration = 1000, // ms
interval = setInterval( function(){
// do your tests here
// ..................
// when element loses focus, we stop checking:
if( ! $input.is( ':focus' ) ) clearInterval( interval );
}, intervalDuration );
} );
Tested on Chrome, Mozilla and even IE.
I've realised via monitorEvents that at least in Chrome the keyup event is fired before the autocomplete input event. On a normal keyboard input the sequence is keydown input keyup, so after the input.
What i did is then:
let myFun = ()=>{ ..do Something };
input.addEventListener('change', myFun );
//fallback in case change is not fired on autocomplete
let _k = null;
input.addEventListener( 'keydown', (e)=>_k=e.type );
input.addEventListener( 'keyup', (e)=>_k=e.type );
input.addEventListener( 'input', (e)=>{ if(_k === 'keyup') myFun();})
Needs to be checked with other browser, but that might be a way without intervals.
I don't think you need an event for this: this happens only once, and there is no good browser-wide support for this, as shown by #xavi 's answer.
Just add a function after loading the body that checks the fields once for any changes in the default value, or if it's just a matter of copying a certain value to another place, just copy it to make sure it is initialized properly.
I have a checkbox on which i am trying to send an ajax request based on its position. It is true by default. I want to be able to click it, and get a dialog that asks me if I want to discard my changes,and this dialog depends on the fact that the checkbox is not yet false.
$("input[type='checkbox']").click(function(evt) {
evt.preventDefault();
alert(this.checked);
if(checkEdited()){
var result = confirm("Do you want to continue?");
}
});
function checkEdited(){
var checkbox = $("div.managerContent input[type='checkbox']");
if(!checkbox.checked){
return false;
}
else{
//check other stuff
}
}
And everytime, I am getting false in the alert. In the browser, when I click the checkbox the check goes away, i get the alert, and then the check comes back.. checkEdited() is also used in other places
Everywhere I look to find how to stop a checkbox change event and assign it a value later just tells me to use .click and e.prenventDeafult()
Any ideas? Thanks so much!
You should attempt to capture the event before the click is complete, you can do this with mousedown like so:
$("input[type='checkbox']").on('mousedown',function(evt) {
evt.preventDefault();
alert(this.checked);
});
Here is a demo with a working example of capturing it before it changes
JSFIDDLE DEMO
$(document).ready(function () {
$(document).on('body', function () {
var visibleInput = $("input[type=text]").filter(':visible');
visibleInput.focus();
});
});
it doesn't work this way I wonder why. No error in the console.
Try this
$(document).ready(function(){
$("input[type=text]").filter(':visible').focus();
});
How many inputs are there on the page?
Only one input can have focus at a time... I would assume that that variable declaration would pick up each input.
I think there no body events in either JQuery or javascript. Normally you can't focus multiple elements at a time so use second one else it will focus on last textinput only.
$(document).ready(function(){
var visibleInput = $("input[type=text]").filter(':visible');
visibleInput.focus(); //Focus last textinput with visible not first one.
});
If you want focus first textinput with visible try this one
$("input[type=text]").filter(':visible').first().focus();
I'm working on my first program using jQuery, but I'm having an issue. I have a dialog pop up on pageLoad that asks the user to select a date and a turn. Right now, for debugging purposes, I have it alert every time .click() executes, and for some reason, it seems like it executes before the user clicks and immediately afterward.
There are three radio buttons, Turns 1, 2, and 3. When the user clicks Turn 1, the alert should say "1". When the user clicks Turn 2, the alert should say "2", etc. But for some reason, it alerts the previous value as well as the new one. I searched all of my code, and there is only one alert, so I can't figure out what is calling click() twice. I've tested it in IE and Chrome and it happened both times.
This is my .click() function:
$("#turn-radio")
.click(function () {
turnvalue = $("input[name='turn-radio']:checked").val();
alert(turnvalue);
});
If you check this jsfiddle, you'll see the rest of my code, which will hopefully make it easier to figure out what my problem is.
Thanks!
You need to change selector: as your radio button IDs are different and you were giving name as a selector that's why you were facing that problem:
$("input[name='turn-radio']")
.click(function () {
turnvalue = $("input[name='turn-radio']:checked").val();
alert(turnvalue);
});
Updated Fiddle
changing
$("#turn-radio") to $("#turn-radio label")
causes only one popup displaying the previous value
But, personally i would
$("#turn-radio input").change( function() { /* do stuff */ } )