disable enable button on keypress - javascript

i want to enable button when there is some value in text box
this is working fine all most but for one value it will fail
like is enter 1 in text box
http://jsfiddle.net/akash4pj/YhQN4/
js
<script>
$(document).ready(function(){
$("#textbx").keypress(function(){
if ($("#textbx").val().length > 0) {
$("#btn").removeAttr('disabled');
}
});
$("#textbx").blur(function(){
if ($("#textbx").val().length ==0) {
$("#btn").attr('disabled','disabled');
}
});
});
</script>
html code
<input id="textbx" type="text" /><button id="btn" disabled="disabled">go</button>

Use keyup instead of keypress, like this:
$("#textbx").blur(function () {
if ($("#textbx").val().replace(/\s{1,}/g, "").length == 0) {
$("#btn").attr('disabled', 'disabled');
}
});
Also, I've added .replace(/\s{1,}/g, "") in the code as well. This ensures (indirectly) that if the user only types spaces, the button will still be disabled when the text input is blurred.
Fiddle.

The keypress event occurs before the browser processes the key, i.e. before the character is appended to the input value, so when the first key is pressed, the textbox is still empty when your functions checks the value length.
The keyup event occurs after the browser has appended the character to the input, so if you trigger on keyup instead of keypress your code should function the way you want.

I'd suggest:
$("#textbx").on('keyup blur', function() {
$("#btn").prop('disabled', $.trim(this.value).length === 0);
});

As mentioned in other answers you should use keyup, but you don't need to listen for blur as well:
$("#textbx").keyup(function(){
if ($("#textbx").val().trim().length > 0) {
$("#btn").removeAttr('disabled');
}
else
$("#btn").attr('disabled','disabled');
});
Fiddle

Related

<input type="date"> event listener: How to distinguish mouse select vs. keyboard input

I use the native HTML date pickers. I want to achieve that the parent form is submitted when a date is selected by the datepickers browsers provide.
If the date is input by keyboard, I only want to submit if the enter key is pressed or on focusout.
Now my problem is that I cannot distinguish between date picker input and keyboard input, at least in Firefox. Some examples:
$(this).on('input', function(event) {
console.log(event.type);
}
This always logs 'input', no matter what I do - I would have expected that to be either "click" or "keydown" or something alike.
The on('click') handler only fires when I click on the input field, not when I click something in the date picker...
Can someone push me in the right direction?
Thanks alot
Philipp
I did a workaround which is close to what I want:
$('#eooMainForm input[type="date"]')
.each(function() {
$(this).data('serialized', $(this).serialize());
$(this).on('focusout', function() {
if($(this).serialize() != $(this).data('serialized')) {
$("#eooMainForm").form('submit');
}
});
$(this).on('keypress', function(event) {
$(this).data('byKeyPress', 1);
});
$(this).on('click', function(event) {
$(this).data('byKeyPress', 0);
});
$(this).on('change', function(event) {
//if change was done by date picker click
if($(this).data('byKeyPress') != 1 && $(this).serialize() != $(this).data('serialized')) {
$("#eooMainForm").form('submit');
}
});
});
So a keypress event listener sets the "flag" "byKeyPress" to 1, while a click events listener sets it to zero. This way, I can determine in the change event listener what caused the change.
The only situation where this does not work is when a user starts typing the date but then selects it by clicking the datepicker. I can live with that.
You'll need to attach an event which supports both event types. Using JQuery: $('a.save').bind('mousedown keypress', submitData(event, this));
Then create a JS condition:
function submitData(event, id)
{
if(event.type == 'mousedown')
{
// do something
return;
}
if(event.type == 'keypress')
{
// do something else
return;
}
}
You can find all the list of event in this image.
$('input').on('blur', function(event) {
alert(event.type);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
You can apply all event like the above example. Above example applied blur event on input.

Replace class on clicking outside div

I have some javascript which essentially removes a class which has a background image on focus, i.e clicking in the input box (which has the background image).
The code is as follows:
$(function(){
$("#ets_gp_height").focus(function(){
if(!$(this).hasClass("minbox")) {
} else {
$(this).removeClass("minbox");
}
});
});
This works well, and removes .minbox when the user clicks within the input field, however what i want to do is if the user makes no changes to the input field, it should add the class back in as per at the beginning. At the moment, once the user clicks once, the class is gone for good, i would like it to come back if the user makes no changes to the input box, so for example clicks the input field but then clicks back out again without entering anything.
Any help? Possible?
I'm assuming you don't want the class .minBox to be added if the user has entered a value, but only if they decided not to enter anything, or chose to erase what they had entered.
To do this, you can use the blur event and check if there's anything entered:
$("#ets_gp_height").blur(function()=> {
if($(this).val().length < 1) $(this).addClass('minBox');
});
This will work for TABing out of the input and CLICKing out of it.
$(document).on("blur", "#ets_gp_height", function(){
if($(this).val() == '') {
$(this).addClass('minBox');
}
});
This code will add class 'minBox' when ever user goes out of input field without entering any value.
A working example, with and without jQuery:
Note: with onblur solution, method is called each time the field is blured, even when the value hasn't changed. with onchange solution, method is called only when the value has changed. That why onchange is a better solution.
WITHOUT JQUERY
function onChange(input){
input.value.length > 0 || setClassName(input, 'minbox') ;
}
function onFocus(input){
if(input.className == 'minbox')
{
input.className = '' ;
}
}
function setClassName(o, c){ o.className = c; }
input.minbox {background-color:red;}
<input type="text" id="ets_gp_height" class="minbox" onchange="onChange(this)" onfocus="onFocus(this)">
WITH JQUERY:
$(function(){
$("#ets_gp_height").change(function(){
$(this).val().length > 0 || $(this).addClass("minbox");
})
$("#ets_gp_height").focus(function(){
if(!$(this).hasClass("minbox")) {
} else {
$(this).removeClass("minbox");
}
});
});
input.minbox {background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ets_gp_height" class="minbox">

How to correctly change value of input form to be noticed by "change" event?

I'm trying to create keyboard for input extra symbols in dynamically created fields. I'm using on() function to handle blur and change events of input form. I'd like to input special chars on caret position. Is it possible to make it without using global variables?
Currently change is noticed if I add letters by keyboard and then loose focus or press enter, or if I type (letter and then special character) || (special character and then special character) without loosing blur or even pressing enter.
// checking click targets
var clicky;
$(document).mousedown(function(e) {
clicky = $(e.target);
});
// handling dbclick and enter press
$(document).on("dblclick", "input#word", function (){
$(this).parent().parent().css('background-color', setOnEditColor);
$(this).prop("readonly", false);
$(this).keypress(function(e) {
if(e.which == 13) {
$(this).focusout();
}
});
});
// handling blur on input form
$(document).on("blur", "input#word", function (e){
lastFocus = $(this);
// checking if keyboardLetter element is clicked,
// if yes I want to keep focus on current input
if(clicky.attr('class') == 'keyboardLetter'){
return false;
}
$(this).prop("readonly", true);
$(this).parent().parent().css('background-color', setDefaultColor);
// $(this).trigger("change");
});
// onChange is triggered on blur
$(document).on("change", "input#word", function (){
saveChanges($(this).closest('tr').attr('id'), $(this).val(), 1);
});
//clicking on special characters
$(document).on("click", ".keyboardLetter", function (){
pos = $(lastFocus).caret(); //getting caret position of focused input
lastFocus.val(lastFocus.val().insertAt(pos, $(this).text().trim()));
$(lastFocus).caret(pos+1);
});
Call .change() after setting its value:
lastFocus.val(lastFocus.val().insertAt(pos, $(this).text().trim()));
$(lastFocus).change(); //this line

Keyup event behavior on tab

In this demo, if you place your cursor in the first field and then tab out (without making any changes), the keyup event is fired on the second field. i.e., you are tabbing out of first field and into second field. Is this behavior correct? How can I prevent this from happening? Same applies to shift + tab.
Note:
a) I believe all other keys, printable and non-printable, trigger the keyup event on the first field.
b) The event isn't triggered at all if you keep the tab pressed until it moves out of both fields.
HTML:
<form id="myform">
<input id="firstfield" name="firstfield" value="100" type="text" />
<input id="secondfield" name="secondfield" value="200" type="text" />
</form>
jQuery:
jQuery(document).ready(function() {
$('#firstfield').keyup(function() {
alert('Handler for firstfield .keyup() called.');
});
$('#secondfield').keyup(function() {
alert('Handler for secondfield .keyup() called.');
});
});
A key's default action is performed during the keydown event, so, naturally, by the time keyup propagates, the Tab key has changed the focus to the next field.
You can use:
jQuery(document).ready(function() {
$('#firstfield, #secondfield').on({
"keydown": function(e) {
if (e.which == 9) {
alert("TAB key for " + $(this).attr("id") + " .keydown() called.");
}
},
"keyup": function(e) {
if (e.which != 9) {
alert("Handler for " + $(this).attr("id") + " .keyup() called.");
}
}
});
});
This way, if the Tab key is pressed, you can make any necessary adjustments before handling other keys. See your updated fiddle for an exampe.
Edit
Based on your comment, I revamped the function. The JavaScript ended up being a bit complicated, but I'll do my best to explain. Follow along with the new demo here.
jQuery(document).ready(function() {
(function($) {
$.fn.keyAction = function(theKey) {
return this.each(function() {
if ($(this).hasClass("captureKeys")) {
alert("Handler for " + $(this).attr("id") + " .keyup() called with key "+ theKey + ".");
// KeyCode dependent statements go here.
}
});
};
})(jQuery);
$(".captureKeys").on("keydown", function(e) {
$("*").removeClass("focus");
$(this).addClass("focus");
});
$("body").on("keyup", "*:focus", function(e) {
if (e.which == 9) {
$(".focus.captureKeys").keyAction(e.which);
$("*").removeClass("focus");
}
else {
$(this).keyAction(e.which);
}
});
});
Basically, you give class="captureKeys" to any elements on which you want to monitor keypresses. Look at that second function first: When keydown is fired on one of your captureKeys elements, it's given a dummy class called focus. This is just to keep track of the most recent element to have the focus (I've given .focus a background in the demo as a visual aid). So, no matter what key is pressed, the current element it's pressed over is given the .focus class, as long as it also has .captureKeys.
Next, when keyup is fired anywhere (not just on .captureKeys elements), the function checks to see if it was a tab. If it was, then the focus has already moved on, and the custom .keyAction() function is called on whichever element was the last one to have focus (.focus). If it wasn't a tab, then .keyAction() is called on the current element (but, again, only if it has .captureKeys).
This should achieve the effect you want. You can use the variable theKey in the keyAction() function to keep track of which key was pressed, and act accordingly.
One main caveat to this: if a .captureKeys element is the last element in the DOM, pressing Tab will remove the focus from the document in most browsers, and the keyup event will never fire. This is why I added the dummy link at the bottom of the demo.
This provides a basic framework, so it's up to you to modify it to suit your needs. Hope it helps.
It is expected behavior. If we look at the series of events happening:
Press Tab Key while focus is on first text box
Trigger key down event on first text box
Move focus to second text box
Lift finger off tab key
Keyup event is triggered on second text box
Key up is fired for the second text box because that is where it occurs since the focus was shifted to that input.
You can't prevent this sequence of events from happening, but you could inspect the event to see what key was pressed, and call preventDefault() if it was the tab key.
I was recently dealing with this for a placeholder polyfill. I found that if you want to capture the keyup event in the originating field, you can listen to the keydown event and fire the keyup event if a tab was pressed.
Instead of this:
$(this).on({'keyup': function() {
//run code here
}
});
Change to this:
$(this).on({'keydown': function(e) {
// if tab key pressed - run keyup now
if (e.keyCode == 9) {
$(this).keyup();
e.preventDefault;
}
},
'keyup': function() {
//run code here
}
});
I ended up using this solution:
HTML:
<form id="myform">
<input id="firstfield" name="firstfield" value="100" type="text" />
<input id="secondfield" name="secondfield" value="200" type="text" />
</form>
jQuery:
jQuery(document).ready(function () {
$('#firstfield').keyup(function (e) {
var charCode = e.which || e.keyCode; // for cross-browser compatibility
if (!((charCode === 9) || (charCode === 16)))
alert('Handler for firstfield .keyup() called.');
});
$('#secondfield').keyup(function (e) {
var charCode = e.which || e.keyCode; // for cross-browser compatibility
if (!((charCode === 9) || (charCode === 16)))
alert('Handler for secondfield .keyup() called.');
});
});
This solution doesn't run the alert if the key is tab, shift or both.
Solution: http://jsfiddle.net/KtSja/13/

Simulate an "ontype" event

I want to simulate the Google Search effect that even with the search box not focused, the user can start typing and the input box will capture all keyboard strokes.
I have looked for an ontype event, but haven't found anything. I know that the event object in callbacks for events like click has keyboard information, but I don't think this is what I'm after.
This does the job:
$(document).on('keydown', function() {
$('input').focus();
});
HTML:
<input type="text" id="txtSearch" />
Javascript:
var googleLikeKeyCapture = {
inputField : null,
documentKeydown: function(event) {
var inputField = googleLikeKeyCapture.inputField;
if(event.target != inputField.get(0)) {
event.target = inputField.get(0);
inputField.focus();
}
},
init: function() {
googleLikeKeyCapture.inputField = $('#txtSearch');
$(document).bind('keydown', googleLikeKeyCapture.documentKeydown);
googleLikeKeyCapture.inputField
.focus(function() {
$(document).unbind('keydown');
})
.blur(function() {
$(document).bind('keydown', googleLikeKeyCapture.documentKeydown);
});
googleLikeKeyCapture.init = function() {};
}
};
$(googleLikeKeyCapture.init);
Also you can find jsFiddle example here
EDIT :
And now it's a jQuery plugin. :) If keydown occures in a textarea or input field it doesn't capture keys, anything else goes to designated input field. If your selector matches more than one element it only uses the first element.
Usage: $('#txtSearch').captureKeys();
The event you are after is onkeypress.
Try this jQuery Text Change Event plugin:
http://www.zurb.com/playground/jquery-text-change-custom-event

Categories