Why submit button is not enabled immediately on change to textfield? - javascript

With this code The button will become enabled only after:
I type something in textfield
I change the focus out of the textfield.
How can I get the button to enable as soon as something is typed in?
function validateAmount(){
if ($('#parlay-amount-textfield').val().length > 0) {
$("#parlay-submit-button").prop("disabled", false);
}
else {
$("#parlay-submit-button").prop("disabled", true);
}
}
$(document).ready(function(){
validateAmount();
$('#parlay-amount-textfield').change(validateAmount);
});

The change event doesn't fire until focus leaves the input field.
You can use the input event instead on modern browsers, which fires immediately. Or a combination of events to support slightly older browsers: input change paste click which you can respond to immediately and then keydown which you need to respond to after a very brief delay. But I think input's support is very good these days, with the notable exception of IE8 which doesn't support it.
Example with just input:
function validateAmount() {
if ($('#parlay-amount-textfield').val().length > 0) {
$("#parlay-submit-button").prop("disabled", false);
} else {
$("#parlay-submit-button").prop("disabled", true);
}
}
$(document).ready(function() {
validateAmount();
$('#parlay-amount-textfield').on("input", validateAmount);
});
<input type="text" id="parlay-amount-textfield">
<input type="button" id="parlay-submit-button" value="Send">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Example with input change paste click handled immediately and keydown after a very brief delay:
function validateAmount() {
if ($('#parlay-amount-textfield').val().length > 0) {
$("#parlay-submit-button").prop("disabled", false);
} else {
$("#parlay-submit-button").prop("disabled", true);
}
}
$(document).ready(function() {
validateAmount();
$('#parlay-amount-textfield')
.on("input change paste click", validateAmount)
.on("keydown", function() {
setTimeout(validateAmount, 0);
});
});
<input type="text" id="parlay-amount-textfield">
<input type="button" id="parlay-submit-button" value="Send">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Side note: FWIW, validateAmount can be a bit shorter:
function validateAmount() {
$("#parlay-submit-button").prop("disabled", $('#parlay-amount-textfield').val().length == 0);
}
And if just spaces isn't a valid value, you might consider throwing a $.trim() around $('#parlay-amount-textfield').val() (or on modern browsers, using $('#parlay-amount-textfield').val().trim()).

Since we are using the change event the input fields focus tends to say that user has not yet ended up his field with data.so only after the focus is moved the button gets enabled u can use the above Link for further clarifications
[1]"https://jsfiddle.net/MuthuramanNagarajan/gs2sff6j/"

Related

How to enable a button on pasting something using mouse?

I have a textbox and a button. The functionality is that whenever textbox is empty, button is disabled and if not empty then button is enabled. I am doing this using following jQuery code:
$('#user_field').keyup(function(){
if($(this).val().length !=0){
$('#btn_disabled').removeAttr('disabled');
$('#btn_disabled').attr('class', 'upload_button_active');
}
else{
$('#btn_disabled').attr('disabled',true);
$('#btn_disabled').attr('class','upload_button_inactive');
}
})
However, when I am trying to paste input using mouse, the button is not enabling. I have tried binding other mouse events like mousemove, but for that to work we have to move the mouse after pasting. I want to avoid that. Suggest something else.
You should use 'input'
$("#tbx").on('input',function(){
var tbxVal=$(this).val();
if(tbxVal.length===0){
$("#btn").prop("disabled",true);
}else{
$("#btn").prop("disabled",false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tbx">
<button id="btn" disabled>Button</button>
You can use the paste event and retrieve the value of the input inside a setTimeout
$('#user_field').on('paste input', function() {
setTimeout(() => {
if ($(this).val().length !== 0) {
$('#btn_disabled').removeAttr('disabled');
$('#btn_disabled').attr('class', 'upload_button_active');
} else {
$('#btn_disabled').attr('disabled', true);
$('#btn_disabled').attr('class', 'upload_button_inactive');
}
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='user_field'>
<button id='btn_disabled' disabled='disabled'>Click</button>
Just Call the function on change.
It will take your input event from mouse as well.
$("#textBox").change(function(
var val=$(this).val();
if(val.length===0){
$("#btn").prop("disabled",true);
}else{
$("#btn").prop("disabled",false);
}
});

IE11 doesn't want to focus on `disabled` element

I'm trying to force text to only be enter-able in one of two text fields.
When one field loses focus I check its value, and if it is not empty I disable the other text field.
Here's an example:
HTML:
<div class="container">
<label for="textOne">textOne</label>
<input type="text" id="textOne"/>
</div>
<div class="conatiner">
<label for="textTwo">textTwo</label>
<input type="text" id="textTwo"/>
</div>
jQuery:
$("#textOne").on('focusout', function() {
console.log("focusout::\t"+this.id);
if( $("#textOne").val() == "") {
$("#textTwo").prop('disabled', false);
} else {
$("#textTwo").prop('disabled', true);
}
});
$("#textTwo").on('focusout', function() {
console.log("focusout::\t"+this.id);
if( $("#textTwo").val() == "") {
$("#textOne").prop('disabled', false);
} else {
$("#textOne").prop('disabled', true);
}
});
This works just fine in Chrome and Firefox, but it appears that IE11 does not support focus on disabled elements.
The only solution I've found is in this question, which is to use the readonly attribute, instead of the disabled attribute. This isn't a desirable solution for my application.
Is there a way to achieve this in IE11, while still using the disabled attribute?
What is the reason IE11 does not support focus on disabled attributes?
Thanks in advance for any suggestions and answers.
EDIT: here is an example on jsFiddle which, when ran on IE11 will reproduce the issue explained in the post https://jsfiddle.net/ftqbop7a/2/
Simple as that, instead of focusout use the input event:
$("#textOne").on('input', function() {
if( $.trim($("this").val()) == "") {
$("#textTwo").prop('disabled', false);
} else {
$("#textTwo").prop('disabled', true);
}
});
$("#textTwo").on('input', function() {
if( $("#textTwo").val() == "") {
$("#textOne").prop('disabled', false);
} else {
$("#textOne").prop('disabled', true);
}
});
jsFiddle
To explain: on focusout is too late for IE to get the reference of the last operated input element, while (on)input event will, since it occurs immediately.
Want to simplify your code an WOW your boss?
jsFiddle
var $inp = $("#textOne, #textTwo");
$inp.on("input", function() {
$inp.not(this).prop("disabled", $.trim(this.value));
});

How to avoid keydown delay with jQuery?

GOAL:
When a user types character in a text box, make a button appear. When the user clears the text box using the backspace key but holds down that key for a few extra seconds, hide the button instantly.
ISSUE:
If a user types in a single character, and uses the backspace to remove it—by holding down the backspace key a few extra seconds—there is a delay before the button is hidden. This only happens when the user typed only one character and then held down the the backspace key without letting go. If instead the user typed multiple characters, and then held down the backspace key until the textbox was empty, there was no delay in hiding the button.
<input type="text" id="tbox"></text>
<button type="button" id="btn" style="display:none;">push me</button>
$('#tbox').on('keydown keypress keyup',function(){
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
});
JSFIDDLE:
http://jsfiddle.net/odkut0dh/
A little walkthrough the situation :
Assuming that <input> value is "x" and you type backspace :
- When the keydown event fires the input's value is still "x".
- When the keypress fires, it still "x".
If you don't release the key :
__ keydown fires again, after some delay, depending on os I guess value is now "".
__ keypress fires again, value is still "".
__ When you release the key, keyup fires, value is "".
If you do release the key :
__ keypress fires directly, value is "".
The solution For IE10+ is to use the input event which will fire when the textEditable element's content has changed or, as suggested by #Mayhem, the change event, which won't even listen for key inputs and has a better browser support than input
$('#tbox').on('input change',function(e){
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tbox"></text>
<button type="button" id="btn" style="display:none;">push me</button>
As i've aleady made comments on this one, did a quick google and came across this post which might make it a little easier.. Detect all changes to a <input type="text"> (immediately) using JQuery
So i put it into a fiddle here for you to test: Slight Modded Version
The HTML
<input type="text" value="Some Value" id="text1" />
<button id="btn1">Click Me</button>
The JS
$('#text1').each(function() {
var elem = $(this);
elem.data('oldVal', elem.val());
elem.bind("propertychange change click keyup input paste", function(event){
if (elem.data('oldVal') != elem.val()) {
if (elem.val().length == 0 ) {
$("#btn1").hide();
} else {
$("#btn1").show();
}
elem.data('oldVal', elem.val());
}
});
});
As i dont have to much time to break this code down into sections... By the looks of it.. You dont need the elem.data... Just the bind event...
... ah seems i decided to shorten the code for you...
http://jsfiddle.net/z2ew3fqz/3/
Using the same HTML...
Shortest version i could make from the example given above
The HTML
<input type="text" value="Some Value" id="text1" />
<button id="btn1">Click Me</button>
The JS
$('#text1').bind("propertychange change click keyup input paste", function(event){
if ($(this).val().length == 0 ) {
$("#btn1").hide();
} else {
$("#btn1").show();
}
});
I've quickly tested this on chrome.. mouse/function keys all seem to affect it correctly... Other browsers i'll leave upto the OP to test.. Let me know if any issues in a particular browser..
IE10 seems to be the min support for this .. IE9 might be able to have a js prototype done.. But how important is this for support in your project? to support IE<10?
The Problem is that $('#tbox').val(); is not empty ('') when backspace is pressed. So You have to delay the value check.
When you press down the key, the first thing what happend is that the keydown event is fired, then after that the key action will be performed on the input field.
$('#tbox').on('keydown keypress keyup',function(){
setTimeout(function () {
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
},0);
});
You can prevent repeating keydown by control it on key up by an global variable:
var allow = true;
$(document).on('keydown', function(e) {
if (e.repeat != undefined) {
allow = !e.repeat;
}
if (!allowed) return;
allowed = false;
if($('#tbox').val() !== '') {
$('#btn').css({'display':'block'});
} else {
$('#btn').css({'display':'none'});
}
});
$(document).keyup(function(e) {
allowed = true;
});

jquery focusout == submit

How could I tell if the focusout event occured due to an enter press = form submit or just because of clicking away? The event data which goes to the console is of type "focusout" and has no relevant information
$(".clientrow[clientid="+clientid+"] td."+fieldname+"").bind("focusout", function(event){
console.log(event);
setTimeout(function() {
if (!event.delegateTarget.contains(document.activeElement)) {
$(".clientrow[clientid="+clientid+"] td."+fieldname+"").html(
$(".clientrow[clientid="+clientid+"] td."+fieldname+" input[type=text]").val()
);
}
}, 0);
});
Edit: As Oriol pointed in the comments, this will not work in Mozilla. If you are looking only for webkit browsers, you can try this approach. But as a generic solution, try binding an event on submit button and consecutively set a flag which identifies the element. Based on the element, you can detect whether it's an actual blur or not.
You can look out for relatedTarget property in the event.
Demo: http://jsfiddle.net/GCu2D/782/
JS:
$(document).ready(function () {
$("input").on("blur", function (e) {
console.log(e);
if (e.relatedTarget) {
console.log("Because of button");
} else {
console.log("Just a blur")
}
});
});
HTML:
<form>
<input type="text" />
<button type="button">Submit</button>
</form>
You'll have to replace the focusout with blur event. When the blur is due to a click on a button, the relatedTarget property will have button as value but in other cases it will be null.

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