I have one text box and i am entering data on that text box, what i want to do is: if i will enter 4 characters and will skip that text box by pressing TAB key then one alert will come as"data should be more than 4 characters" and then text box will be auto refreshed. If data entered is more than 4 characters then no alert will come, I was trying by onkeyup event but some where i am doing wrong. Any help please
I don't know what you mean by "then text box will be auto refreshed", so I'm going to guess that you want to put the cursor back into that field. As far as checking the length of the value when tabbing out you want the .change() or .blur() event:
$("input[type=text]").change(function() {
if (this.value.length <= 4) {
alert("Please enter more than 4 characters.");
this.focus();
return false;
}
});
Demo: http://jsfiddle.net/XHKRh/
The blur event will be triggered every time the focus leaves the field; the change event will not be triggered again if the user immediately tabs out of the field again without changing it. I prefer to use change in combination with an additional validation on form submit, so that the user doesn't keep getting pestered with alerts (though actually I wouldn't show an alert at all, I'd put the message on the page next to the field).
How about on blur?
var el = $('#textbox').blur(function(e) {
if (el.val().length > 4) {
return;
}
el.focus();
alert('data should be more than 4 characters');
});
Note that this technique makes for a poor user experience. Showing a message inline with your element would be preferable to preventing the user from interacting with anything else.
There are some points that might result you interesting:
You shouldn't rely ONLY on JavaScript to validate forms, as users can turn it
off and bypass the validation
There is a maxlength property for inputs
You are probably looking for onblur instead of getting the TAB key action, since users
can change focus in other ways
Related
I've added an on 'change' event listener to a type=email input element. When I add a couple space characters into the email field, then lose focus on that element, the change event doesn't seem to be firing.
However, this exact scenario works just fine with type=text input elements.
What's going on?
$('input[type="email"]').change(e => {
console.log('Triggered!');
});
Browser: Chrome Version 63.0.3239.132 (Official Build) (64-bit)
I originally said that it looks like there is an automatic trim operation performed on email fields because the length of the value is coming back at 0 after typing some spaces and leaving the field, but upon returning to the field, the spaces remain in the element, so they aren't getting trimmed out.
I suspect that, because spaces are not valid for this input type, they are not considered part of the value, thus the value doesn't change when you enter them and the change event doesn't fire.
Type some spaces in the field and then hit TAB to leave the field, but then return to the field. The spaces will still be there.
$('input[type="email"]').on("blur", function(e){
console.log(this.value.length);
});
$('input[type="email"]').on("change", function(e){
console.log("Change fired!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="email">
You can use something like that:
$('input[type="email"]').on('focusout', {
console.log('Triggered!');
var $trig = $(this);
$trig.attr('trimmed', $trig.val().toString().trim());
$trig.val( '').val($trig.attr('trimmed'));
});
But, as answered above, input[type="email"] does not count whitespaces. It is only works as fast hack;
I am facing the same problem with React, and I don't want to reflect the error on the onBlur event (as other solutions here). I don't think an error should be reflected in any input by the simple fact of removing the mouse from that input. For me that's not User friendly,... AT ALL.
Why?
Because the User might have decided to remove the mouse from that
Input only because he/she simply wants to copy something from somewhere else first,... and then past it there (and/or to past it somewhere else). So technically there is no mistake there yet.
Because I simply want to fill another input field of the form first.
Why? Becase that's precisely the field's value I already copied from
somewhere else, so that's the value I have stored in clipboard, and
it doesn't goes where my mouse landed by default. Or simply because
I just want to! I'm the User, so I can choose the order to
fill the form!
For me is more than enough with validating what the User has written and/or removed/deleted from the Inputs (onChange validation) AND also what the User finally decides to send (onSubmit validation). A proper combination of onChange and onSubmit validation is the perfect healthy balance between thoroughness and User friendly.
A Solomonic "solution":
I am using a custom validation hook. As I can not change the behavior of the input with a type email regarding the white spaces in an OnChange event,... then I decided to use a workaround, which is simply avoiding the typing of white spaces and that's it, as the onChange event won't trigger anyway.
const preventWhiteSpaceOnKeyDown = (e) => {
if (e.key === " ") {
e.preventDefault();
}
}
.
.
.
<input
type={"email"}
id='commentEmail'
name='commentEmail'
required={true}
autoFocus={true}
ref={emailInputRef}
value={emailState}
onChange={emailInputChangeHandler}
onKeyDown={preventWhiteSpaceOnKeyDown}
/>
This is not a "solution". There is no clean solution for this. But after this at least my input[type=email] element won't hold useless white spaces.
input[type="email"] does not fire change event, use blur event instead:
$('input[type="email"]').blur(function(){
console.log('blur event is fired.');
});
I am trying to figure out how to do something but can not figure out the correct terminology to do so.
What I am trying to do is have a textbox (#price) that when clicked once it will open up a pdf calculator that will then either prefill the textbox when completed or will then allow the user to enter the amount in. But I also want this to work if the textbox is "tabbed" over to also instead of the onClick. (Maybe onBlur) Basically anytime that textbox is used I need it to work like that. But how do I make the onClick know when the amount is ok to be entered or if the calculator needs to open?
What also makes this tricky is I need to have an On/Off switch basically a checkbox that when checked it allows that pop up pdf calculator and when its not checked it just ignores it and allows the price to be entered still.
Does anyone have any suggestions or pointers in how I can achieve this goal?
1. A textbox (#price) that when click once it will open up a pdf calculator
Use jQuery's click() handler or bind("click", ...)
var $price = $("#price");
$price.click(function() {
$("#pdf_calculator").fadeIn();
});
2. But I also want this to work if the textbox is "tabbed" over to also
Use the focus event to know when an input is active (i.e, has been "tabbed" to). Alternatively, the blur event can be used if you want to know when a user is "leaving" the input field. ('blur' is the opposite of 'focus')
$price.on("focus click", function() {
$("#pdf_calculator").fadeIn();
});
3. But how do I make the onClick know when the amount is ok to be entered or if the calculator needs to open?
Grab the amount typed in by the user, convert it to a numerical value, then perform your validation steps.
$price.on("focus click", function() {
// Do some validation checking on the amount entered.
var enteredValue = parseFloat($price.val());
if (!isNaN(enteredValue) && enteredValue > 0) {
$("#pdf_calculator").fadeIn();
}
});
4. What also makes this tricky is I need to have an On/Off switch basically a checkbox that when checked it allows that pop up pdf calculator and when its not checked it just ignores it and allows the price to be entered still.
Simply check that the checkbox is checked using jQuery's is(":checked") then combine the steps above, and your fully working code looks like this:
var $price = $("#price");
$price.on("focus click blur", function() {
// your checkbox element
var checkbox = $("#show_calculator");
// Check if the checkbox is checked
if (checkbox.is(":checked")) {
// convert the entered string to a number
// then validate it according to your needs
var enteredValue = parseFloat($price.val());
if (!isNaN(enteredValue) && enteredValue > 0) {
// if all conditions are met,
// show the pdf calculator
$("#pdf_calculator").fadeIn();
}
}
});
Click here to review a working jsfiddle of these ideas.
As for the pdf form (and getting values in and out again of a pdf form) there isn't a straight-forward method that doesn't involve a 'hack' (that may or may not work across different browsers). If the pdf only has ONE input, then you can capture the keyboard events on your form popup, and send them back to the HTML form (which is an ugly hack), but if this were my project, I would just convert the pdf functionality to javascript, and then you have all the freedom you need, and your calculator is 100% compatible with the rest of your application.
Hope this helps!
The event(s) you are looking for is onFocus and onBlur. I would bind a function to the onFocus event that first checks if the corresponding checkbox has a "true" (or "checked") value, then continue if it does and do nothin if it doesn't.
I'd create an example in jsfiddle for you if I wasn't answering this from my phone.
Bind event handler to focus event (blur is for when control looses focus).
$("#price").on({
"focus": eventHandler
})
Then in your eventHandler() check if calculator needs to be invoked, by checking if it's already opened: $("#calculatorDiv").is(":visible"), and checking if your checkbox is 'checked': $("#checkboxId").is(':checked'), and depending on that open it.
I have a small jquery code which hide/show an icon when an input field is empty/have something
My code is:
$("#pass1").on("change",function(){
if($("#pass1").val())
$("#showpass").show();
else
$("#showpass").hide();
});
But this occures only when user finish typing and moves to next field or removes focus but I want to do this while user is typing i.e it should occur as soon as user either enters or delete an single character.How can I do this ?
Use .keyup(). Try this:
$('#pass1').keyup(function() {
//your code goes here
});
I'm making a page for a friend and I have a hidden text field and when the user types the text is transposed into a div so that it looks like they're typing on the screen rather than in an input field.
Here is a link to the page: http://merkd.com/godis.php
Here is the function that I use to respond to the key strokes:
$('#hiddenInput').keydown(function() {
var input = $('#hiddenInput').val();
var html = '<div style="float: left;">'+input+'</div><div id="cursor">|</div>';
$('#typingArea').html(html);
});
The text-field is visible right now so that you can see the problem. When text is entered or deleted, it doesn't respond until the next keypress. So if I type a single letter, nothing shows up until I type the next letter.
I looked at the jQuery .on() documentation but I couldn't find anything on this. Any help is much appreciated.
P.S. I know it should be in a separate question, but is there an easy way to make a text-field always in focus? I want to make it so that no matter where the user clicks or whatever, if they type, the text will still show up.
Use .keyup() event because when you first press (keydown), the letter is never typed so the var html is getting previous value. For second part you can bind keypress event in document to focus your input field.
Now I am developing a bar code based attendance system . Any there any javascript event can solve once the text field has detected the value has 10 characters, the text field will be fired and i can able to get the value.
Is there any solution ?
I'm not sure what you mean by "the text field will be fired", but you can find out when the 10th character is entered by binding to the keyup event:
document.getElementById("example").onkeyup = function() {
if(this.value.length === 10) {
console.log("ok");
}
};
It would be better to use addEventListener or attachEvent rather than setting the onkeyup property, but I'll leave that up to you.
Here's a working example.
you can check the length of the text input box value on every keypress and make a function call when its the 10th character.