jQuery .keyPress() - How to get value of input which triggered event? - javascript

Trying to do some jQuery validation (without the plugin - please no answers like "Just use the validate-js plugin").
I'm wiring up a client-side event handler keypress for each "required field" on doc ready:
$(document).ready(function() {
$('#myform input.required').each(function() {
$(this).keypress(onRequiredFieldKeyPress);
});
});
Which correctly fires this event on each keypress:
function onRequiredFieldKeyPress() {
if ($(this).val().trim() == '') {
$(this).next('em').html('*').show(); // show req field indicator
} else {
$(this).next('em').html('*').hide(); // hide req field indicator
}
}
But $(this).val() is always null/empty. Looks like it's passing in an "HTMLInputElement" which is what i'd expect, but it's almost like i have to project this into some other jQuery type?
Essentially i'm trying to do this: on the keypress event of any field which i have wired-up (which are all input elements), call that function. In that function, if that field has a value of '' (empty), then show a hidden field which displays a required field indicator.
I don't really care which actual element fired the keypress, as the behaviour of my logic will be the same. I just need to get the actual value.
Am i missing something?

Because you are using key-press event. Key press has 3 phase:
1. Key down: when key is press
2. Key hold: key is hold down
3. Key up: key is release
In your case, problem can be solved by using keyup event
$(document).ready(function() {
$('#myform input.required').each(function() {
$(this).keyup(onRequiredFieldKeyPress);
});
});

Try using event.currentTarget, where event is the first param of your function.
See here: http://api.jquery.com/event.currentTarget

Related

Does 'keypress' jQuery event fire before an inputs value is updated?

I have a keypress event listener on an input field to confirm a password. I want the button on the page to be disabled until the password and confirm-password fields have matching values. I am using the .keypress() jQuery function, but it seems to always be one character behind what I expect it to be?
Here is the code
$('#confirm').keypress(function() {
console.log('#confirm').val();
if($('#password').val() == $('#confirm').val()) {
$('button').removeProp('disabled');
console.log("yes");
} else {
console.log("no");
}
});
But when I inspect element and look at the console window on my page, the first time the event is fired it prints the form value as blank. Then when I enter a second character, it prints only the first, and when I type a third character it prints the first two, etc.
For example, if I put asd into the password field and begin typing the same into the confirm field the output will look like this:
<blank>
no
a
no
as
no
So at this point both password and confirm fields have "asd", but I need to enter an extra character before that is recognized and the "disabled" property is removed from the button.
I have tried using .change() instead of .keypress() but that doesn't fire until the input field loses focus, which is not what I want.
I want the button on the page to be disabled until the password and confirm-password fields have matching values
If this is your goal, you can add event listeners to both inputs that call a validation function:
$('#password').on("input", function() { validatePassword(); });
$('#confirm').on("input", function() { validatePassword(); });
function validatePassword() {
if($('#password').val() && $('#confirm').val() && $('#password').val() == $('#confirm').val()) {
$('button').prop('disabled', false);
} else {
$('button').prop('disabled', true);
}
}
It also may be worthwhile adding an ID to the button. Using 'button' would enable/disable all elements on the page.
Example: https://jsfiddle.net/doL4t9vv/1/
I had the same problem few months ago.
Try to use the keyup function from Jquery.
Keypress event is fired when you press the key, so the input is not fill yet.
Keyup event is fired when you release the key.
Can use input event and simplify this down to
var $passwords =$('#confirm, #password').on('input', function() {
var thisValue = this.value.trim();
// does this input have value and does it match other
var isValid = thisValue && thisValue === $passwords.not(this).val().trim();
// boolean used for disabled property
$('button').prop('disabled', !isValid);
});

How to Capture changing value of textbox

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.

How to call a function when default browser autocomplete list item selected [duplicate]

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.

Running check on empty input type of text

How would I run a check after a keypress function to see if an inputs value was empty so I can do another action.
For example.
$("input[name=amount]").keypress(function() {
$("table[name=apply]").show();
});
I want to hide the table if the user deletes all the keystrokes.
$("input[name=amount]").keyup(function() {
if (this.value == '') {
$("table[name=apply]").hide();
} else {
$("table[name=apply]").show();
}
});
You will probably want to use either the keyup or change event so the value of the text-box has changed before the event handler runs. The keypress event fires before the value of the input has changed, so for instance if the input is blank and a key is entered, the value in the event handler would still read as blank.
Here is a demo: http://jsfiddle.net/jasper/C5KPq/
Use the keyup() method to perform the check after the keystroke has finished:
$("input[name=amount]").keyup(function() {
if(this.value === ''){....}
});
If you bind to the keypress or keydown events, the value of the input inside your event handler will not yet have been affected by the keystroke. This is why you need to bind to keyup instead.
You can try this using keyup event instead of keypress because keypress will not give you the latest value.
$("input[name=amount]").keyup(function() {
//Here this points to the textbox element and value gives its content
if(this.value == ''){
$("table[name=apply]").show();
}
});
If you want to toggle the table the you can use this.
$("input[name=amount]").keyup(function() {
$("table[name=apply]").toggle(this.value != '');
});
toggle(showOrHide) - Display or hide the matched elements.
Demo
you can use the following
if( $(this).val() == "")
try:
if ($("input[name=amount]").val() == '') // input is empty

Jquery : how to trigger an event when the user clear a textbox

i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />

Categories

Resources