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

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));
});

Related

Disable and enable function in Jquery

I have a text input in html that is affected by a function exectued by .change() events from different radios and checkboxes. I'm trying to make it so that if a user types into the input, this function will no longer run when a .change() event happens in the aforementioned radios and checkboxes (the user must still be able to use these radios and checkboxes). However, if the user leaves the input blank and clicks away, the script will run again. I hope is possible.
Here is my take on this so far:
Using.prop('diabled' isnt viable because it completely disables the input, making the user unable to type in it, so I need another solution.
$(function() {
$('#burger-navn').on('input', function() {
$("#burger-navn").prop('disabled', true);
});
//When the input (#burger-navn) is typed into it should be "disabled"
$('#burger-navn').focusout(function() {
if ($(this).val().length == 0) {
$("#burger-navn").prop('disabled', false);
}
});
//But if its clicked out of while its blank, it should be able to run again.
$("#okseinput, #laksinput, #kyllinginput, #vegetarinput").change(function() {
if (!$("#burger-navn").not(':disabled')) { //condition that tests
navngenerator();
}
});
});
To solve this I simply created a separate input tag that I could add and remove disabled attribute from, and check if it has that attribute.
So in html:
<input id="burger-navn" type="text"/>
<input id="toggle" disabled="disabled" style="display:none"/>
jQuery:
var previousValue = $("#burger-navn").val();
$("#burger-navn").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
$("#toggle").prop('disabled', false);
}//This function will remove disabled from #toggle, when a user types into #burger-navn
});
$('#burger-navn').focusout(function() {
if ($(this).val().length == 0) {
$("#toggle").prop('disabled', true);
}
});
if ($("#toggle").is(':disabled')) {
navngenerator();
}
$("#okseinput, #laksinput, #kyllinginput, #vegetarinput").change(function() {
if ($("#toggle").is(':disabled')) {
navngenerator();
}
});
$(selector).on('change', function(event){
event.preventDefault();
event.stopPropagation();
// the selected field no longer does anything on change
});
is that what you are looking for?

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

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/"

jQuery script for checking if input has any value. Issue in IE and Chrome

I've got the script for checking if an input isn't empty. It works in Firefox, but if I switch to Chrome or IE, button is enabled even if I submit an empty string. Does anybody know any solution for this issue?
$(document).ready(function(){
$('.comment_button').attr('disabled',true);
$('.comment_input').keyup(function(){
if ($.trim($(this).val()).length != 0) {
$('.comment_button').attr('disabled', false);
}
else
{
$('.comment_button').attr('disabled', true);
}
})
});
There is a typo in your code ' is missing after selector
Use $('.comment_input') instead of $('.comment_input)
In line
$('.comment_input).keyup(function(){
Edit: use .prop() instead of .attr()
Working code JS:
$('.comment_button').prop('disabled', true);
$('.comment_input').keyup(function () {
$('.comment_button ').prop('disabled', $.trim($(this).val()).length == 0);
});
HTML:
<input type="text" class="comment_input" name="somethng"/>
<button class="comment_button">something</button>
Fiddle Demo

click event not trigerred in IE

I am trying to trigger a click event for a button from jquery. it works very well in FF but IE(all versions) seem to ignore it. this is what i have tried so far..
$('#uxcSubmit').trigger('click');
then tried this..
$('#uxcSubmit').click();
just to clear out..even this..
jquery('#uxcSubmit').click();
then even tried this to check if it is a problem of jquery..
document.getElementById('uxcSubmit').click();
nothing seems to help IE..
thanks in advance..
Update: this is the code.. and no i don't have elements of the same id..
<div id="uxcSavingDiv">Click sumbit to save changes...</div>
<input id="uxcSubmit" value="Submit" onclick="return SaveChange();"/>
<script type="text/javascript">
function getFrameValue() {
if (Stage == 0) {
$('#uxsHiddenField').attr("value", "saved");
Stage = 1;
$('#uxSubmit').click();
return false;
}
else {
$('#uxcSavingDiv').innerHTML = "Saving...";
return true;
}
}
</script>
i think i have been clear here
In the code you posted Stage is undefined, IE won't like this. Also $('#uxSubmit').click(); should be $('#uxcSubmit').click();. I also wasn't sure when you were calling getFrameValue(); but it must be done at or after document.ready or the elements won't be there to match selectors on.
I cleaned up the rest to use jQuery methods as well (leaving the in-line for demo, but I'd remove this as well and change it to a click handler), this works fine in IE8:
<div id="uxcSavingDiv">Click sumbit to save changes...</div>
<input id="uxcSubmit" value="submit" onclick="return SaveChange();"/>
<script type="text/javascript">
var Stage = 0;
function getFrameValue() {
if (Stage == 0) {
$('#uxsHiddenField').val("saved");
Stage = 1;
$('#uxcSubmit').click();
return false;
}
else {
$('#uxcSavingDiv').html("Saving...");
return true;
}
}
function SaveChange() {
alert("Value clicked");
}
$(function(){
getFrameValue(); //Trigger it on document.ready
});
</script>
To change that SaveChange() to a bound click handler, remove the onclick and do this on ready:
$('#uxcSubmit').click(SaveChange);
$("#uxcSubmit").closest("form").submit('SaveChange'); //let SaveChange() return true/false
... and remove inline 'onclick' attribute
The relevant code piece from jQuery should be this one
// Trigger an inline bound script
try {
if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) {
if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) {
event.result = false;
}
}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (e) {}
So I guess either this has something to do with bug mentioned 3533 (which I can't check as dev.jquery.com is down at the moment) or there is some other IE bug. btw. do you get any warnings in the error console?

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