I need use two jQuery functions with one ID working on edge and chrome browsers. Chrome works perfect but edge don't.
$("#myInput").keyup(function() {
$("#myInput").val($(this).val().replace(",", "."));
});
$("#myInput").change(function() {
alert("hello world");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" type="text" />
Can you explain me why and how to solve it.
Perhaps you mean this:
Change entering a comma to entering a fullstop and trigger the hello after 1 second of inactivity
var tId;
$("#myInput").on("keypress", function(e) {
clearTimeout(tId);
if (String.fromCharCode(e.which) == ",") {
this.value += ".";
e.preventDefault();
}
tId = setTimeout(function() {
console.log("Hello")
}, 1000);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myInput" />
It seems that in the Edge browser, the change event will not trigger, you could try to trigger the change function in the jquery focusout event, code as below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" type="text" />
<script type="text/javascript">
$(function () {
$("#myInput").keyup(function () {
$("#myInput").val($(this).val().replace(",", "."));
console.log("keyup event trigger");
});
$("#myInput").focusout(function () {
//check whether it is Edge browser
var ua = window.navigator.userAgent;
var edge = ua.indexOf('Edge/');
if (edge > 0) {
$("#myInput").trigger("change");
}
});
$("#myInput").change(function () {
//alert("hello world");
console.log("change event triger");
});
})
</script>
the result as below:
Related
Vanilla JavaScript
In vanilla JavaScript, one can easily enable and disable a button using the following statement:
button.disabled = state;
This works both when humans try to click a button and when buttons are clicked programmatically:
var button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('world');
});
button.disabled = true;
button.click(); // No output
button.disabled = false;
button.click(); // Output : "Hello" and "world
button.disabled = true;
button.click(); // No output
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
This also works when using the MouseEvent interface:
var button = document.getElementById('myButton');
var click = new MouseEvent("click", {
"view": window
});
button.addEventListener('click', function() {
alert('world');
});
button.disabled = true;
button.dispatchEvent(click); // No output
button.disabled = false;
button.dispatchEvent(click); // Output : "Hello" and "world
button.disabled = true;
button.dispatchEvent(click); // No output
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
jQuery
I can't seem to be able to do the same with jQuery, though :
var button = $("#myButton");
button.on("click", function() {
alert("world");
});
button.prop("disabled", true);
button.click(); // Output : "world" and "Hello"
button.prop("disabled", false);
button.click(); // Output : "world" and "Hello"
button.prop("disabled", true);
button.click(); // Output : "world" and "Hello"
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
Both button.prop("disabled", true); and button.attr("disabled", true); simply change the disabled property of the button element, but neither disables the actual click event. This means that events are triggered whenever button.click(); is called, even if the button is disabled!
Additionally, "world" and "Hello" are output in the wrong order.
The simplest code I could come up with to emulate the behavior of the vanilla JavaScript versions, is this :
var button = $("#myButton");
button.on("click", function() {
alert("world");
});
button.disable = (function() {
var onclick = null;
var click = [];
return function(state) {
if(state) {
this.prop('disabled', true);
if(this.prop('onclick') !== null) {
onclick = this.prop('onclick');
this.prop('onclick', null);
}
var listeners = $._data(this.get()[0], "events");
listeners = typeof listeners === 'undefined' ? [] : listeners['click'];
if(listeners && listeners.length > 0) {
for(var i = 0; i < listeners.length; i++) {
click.push(listeners[i].handler);
}
this.off('click');
}
} else {
this.removeProp('disabled');
if(onclick !== null) {
this.prop('onclick', onclick);
onclick = null;
}
if(click.length > 0) {
this.off('click');
for(var i = 0; i < click.length; i++) {
this.on("click", click[i]);
}
click = [];
}
}
}
})();
button.disable(true);
button.click(); // No output
button.disable(false);
button.click(); // Output : "Hello" and "world
button.disable(true);
button.click(); // No output
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
That is, of course, ridiculously convoluted and "hacky" code to achieve something as simple as disabling a button.
My questions
Why is it that jQuery - unlike vanilla JS - doesn't disable the events when disabling a button?
Is this to be considered a bug or a feature in jQuery?
Is there something I'm overlooking?
Is there a simpler way to get the expected behavior in jQuery?
To achieve expected result, you can utilize .isTrigger within jQuery triggered click handler to determine if event is triggered by javascript, and not user action.
Define attribute event listener as a named function, where this can be passed to check disabled property at if condition if alert() is called, or not called.
Use .attr("disabled", "disabled") to set disabled at element, .removeAttr("disabled") to remove attribute; .attr("onclick", null) to remove event attribute onclick handler; .attr("onclick", "handleClick(true)") to reset event attribute.
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input type="button" id="myButton" value="button" onclick="handleClick(this)" />
<script>
function handleClick(el) {
if (el.disabled !== "disabled")
alert("Hello")
}
var button = $("#myButton");
button.on("click", function(e) {
console.log(e);
if (e.isTrigger !== 3 && !e.target.disabled)
alert("world");
});
button.attr("disabled", "disabled");
button.attr("onclick", null);
button.click(); // no output
setTimeout(function() {
button.removeAttr("disabled");
button.attr("onclick", "handleClick(button[0])");
button.click(); // Output : "world" and "Hello"
// click button during 9000 between `setTimeout` calls
// to call both jQuery event and event attribute
}, 1000);
setTimeout(function() {
button.attr("disabled", "disabled");
button.attr("onclick", null);
button.click(); // no output
}, 10000);
</script>
If you take a look to jquery-1.12.4.js at these lines:
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Support (at least): Chrome, IE9
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
//
// Support: Firefox<=42+
// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
if ( delegateCount && cur.nodeType &&
( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
You will you see a different handling of events according to the delegation type:
$(document).on("click", '#btn', function() {
console.log("world");
});
$(function () {
$('#btnToggle').on('click', function(e) {
$('#btn').prop('disabled', !$('#btn').prop('disabled'));
});
$('#btnTestClick').on('click', function(e) {
$('#btn').click();
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<button id="btn">Click Me</button>
<button id="btnToggle">Enable/Disable button</button>
<button id="btnTestClick">Test Click</button>
Of course, if you attach the event like in:
$('#btn').on("click", function() {
alert("world");
});
The behaviour is different and seems strange.
Using .prop() is the right way to do it. I think the issue is in the way that you are "testing" it. See this example where the buttons are disabled/enabled correctly using the toggle button regardless of whether the handler is attached via onclick or with jquery.
window.testFunc = function(event) {
if (!$('#myButton2').prop('disabled')) {
alert("hello");
console.log("hello");
}
}
$(document).ready(function() {
var button = $("#myButton2");
button.on("click", function(event) {
if (!$(this).prop('disabled')) {
alert("world");
console.log("world");
}
});
$('#toggleButton').click(function() {
$('#myButton1').prop('disabled', !$('#myButton1').prop('disabled'));
$('#myButton2').prop('disabled', !$('#myButton2').prop('disabled'));
});
$('#tester').click(function() {
$('#myButton1').click();
$('#myButton2').click();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="myButton1" value="vanilla button (hello)" onclick="window.testFunc(event)"/>
<input type="button" id="myButton2" value="jquery button (world)"/>
<input type="button" id="toggleButton" value="toggle disabled"/>
<input type="button" id="tester" value="test the buttons"/>
The other obvious solution is to just use vanilla javascript. Just because you are using jQuery doesn't mean that everything "must" be done using it. There are some things that are fine to do without jQuery.
EDIT: I edited the snippet showing how you could prevent jquery's .click() from actually triggering the alerts.
You're calling the click function directly 3 times ( button.click() ) which fires regardless of disabled attribute.
The disabled property only responds to click events.
See the updated example:
var button = $("#myButton");
var button2 = $("#myButton2");
button.prop("disabled", false);
button.on("click", function() {
alert("world");
button2.prop("disabled", false);
});
button2.prop("disabled", true);
button2.on("click", function() {
alert("world");
button.prop("disabled", true);
});
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
<input type="button" id="myButton2" value="button2" />
I am trying to disable the textbox using keyup functionality. I have a TextArea and a Text Box. Now i use a keyup operation on backspace key, like if the length of content inside textarea is 3 it should disable the textbox. I also have an alert message which pops when the length of content in text area is 3. Code worked for the pop up but it doesnot worked for the textbox. What am i missing? Please help. Here is my code:
$('#comment').keyup(function() {
if (event.which == 8) {
var txt = $('#comment').val().length;
if(txt == 3)
{
alert("backspace");
$("#text1").attr("diasbled", "diasbled");
}
}
});
And here is the JSfiddle for the purpose.
You have some typo here it should be disabled not diasbled
Try this
$('#comment').keyup(function () {
var len = $(this).val().length;
if (len >= 3) {
$("#text1").prop("disabled", true);
}
else{
$("#text1").prop("disabled", false);
}
});
DEMO
You need to do:
1) this.value.length to get the total characters length of your textarea
2) From jQuery version 1.6 , use .prop() instead of .attr() to set the properties of an element
3) Correct the typo: it should be disabled not diasbled
$('#comment').keyup(function () {
if (this.value.length >= 3) {
$("#text1").prop("disabled", true);
} else {
$("#text1").prop("disabled", false);
}
});
Updated Fiddle
Your code is fine.. but you mispelled the "disabled" in your code. Here's the sample..
<html>
<head>
<title>js test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<input type="text" value="" id="comment" />
<input type="text" value="" id="text1" />
<script type="text/javascript">
$(document).ready(function()
{
$('#comment').keyup(function(e) {
if (e.which == 8) {
var txt = $('#comment').val().length;
if(txt == 3)
{
alert("backspace");
$("#text1").attr("disabled", "disabled");
}
}
});
});
</script>
</body>
Use prop instead of attr also pass event to function
$('#comment').keyup(function (event) { //and event here
if (event.which == 8) {
if ($(this).val().length >= 3) {
$("#text1").prop("disabled", true);
}
}
});
I want to change the maxlength of a textbox with JavaScript or jQuery: I tried the following but it didn't seem to help:
var a = document.getElementsByTagName('input');
for(var i=0; i<a.length; i++) {
if((a[i].type!= 'radio')||(a[i].type!= 'checkbox'))
a[i].maxlength = 5;
}
document.getElementsByTagName('input')[1].maxlength="3";
$().ready(function()
{
$("#inputID").maxlength(6);
});
What am I doing wrong?
Not sure what you are trying to accomplish on your first few lines but you can try this:
$(document).ready(function()
{
$("#ms_num").attr('maxlength','6');
});
The max length property is camel-cased: maxLength
jQuery doesn't come with a maxlength method by default. Also, your document ready function isn't technically correct:
$(document).ready(function () {
$("#ms_num")[0].maxLength = 6;
// OR:
$("#ms_num").attr('maxlength', 6);
// OR you can use prop if you are using jQuery 1.6+:
$("#ms_num").prop('maxLength', 6);
});
Also, since you are using jQuery, you can rewrite your code like this (taking advantage of jQuery 1.6+):
$('input').each(function (index) {
var element = $(this);
if (index === 1) {
element.prop('maxLength', 3);
} else if (element.is(':radio') || element.is(':checkbox')) {
element.prop('maxLength', 5);
}
});
$(function() {
$("#ms_num").prop('maxLength', 6);
});
without jQuery you can use
document.getElementById('text_input').setAttribute('maxlength',200);
set the attribute, not a property
$("#ms_num").attr("maxlength", 6);
$('#yourTextBoxId').live('change keyup paste', function(){
if ($('#yourTextBoxId').val().length > 11) {
$('#yourTextBoxId').val($('#yourTextBoxId').val().substr(0,10));
}
});
I Used this along with vars and selectors caching for performance and that did the trick ..
For those who are facing problem like me with accepted answer:
$(document).ready(function()
{
$("#ms_num").attr('maxlength','6');
});
You may use on focus instead of ready function:
$(document).on('focus', '#ms_num', function() {
{
$(this).attr('maxlength','6');
});
This will make sure to set the maxlength attribute when the input field is focused or selected.
You can make it like this:
$('#inputID').keypress(function () {
var maxLength = $(this).val().length;
if (maxLength >= 5) {
alert('You cannot enter more than ' + maxLength + ' chars');
return false;
}
});
<head>
<script type="text/javascript">
function SetMaxLength () {
var input = document.getElementById("myInput");
input.maxLength = 10;
}
</script>
</head>
<body>
<input id="myInput" type="text" size="20" />
</body>
<head>
<script type="text/javascript">
function SetMaxLength () {
var input = document.getElementById ("myInput");
input.maxLength = 10;
}
</script>
</head>
<body>
<input id="myInput" type="text" size="20" />
</body>
How to lock or disable and again the tab key with javascript?
$(document).keydown(function(objEvent) {
if (objEvent.keyCode == 9) { //tab pressed
objEvent.preventDefault(); // stops its action
}
})
You can do it like this:
$(":input, a").attr("tabindex", "-1");
That will disable getting focus with tab in all links and form elements.
Hope this helps
Expanding on Naftali aka Neal's answer, here's how you'd do it with vanilla JS and both start and stop Tab behavior buttons:
let stopTabFunction = function(e) {
if (e.keyCode == 9) {
e.preventDefault();
}
};
document.getElementById('stopTabButton').onclick = function() {
document.addEventListener('keydown', stopTabFunction);
};
document.getElementById('resumeTabButton').onclick = function() {
document.removeEventListener('keydown', stopTabFunction);
};
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<br/><br/>
<input type="button" id="stopTabButton" value="Stop Tab!"/>
<input type="button" id="resumeTabButton" value="Resume Tab!"/>
Note that this also works for Shift + Tab (reverse direction).
JSFiddle
However, in my case, I wanted slightly different behavior: I wanted to basically lock down Tab focus to a single div. To do this, I placed a div before and after it, gave them both tabindex="0" (document-defined tab order on the div's themselves), to make the outer edges of the div focusable, like so:
<div id="beforeMyDiv"></div>
<div id="myDiv">
<!-- Only want Tab indexing to occur in here! -->
</div>
<div id="afterMyDiv"></div>
Then, I changed the function from earlier to this:
//Get the div's into variables etc.
//...
let forceTabFocusFunction = function (e) {
if (e.keyCode == 9) {
//Force focus onto the div.
if (!myDiv.contains(document.activeElement)) {
if (e.shiftKey) {
afterMyDiv.focus();
} else {
beforeMyDiv.focus();
}
}
}
};
That did the trick nicely.
On Neal answer, I'd only add:
if (objEvent.keyCode == 9) { //tab pressed
return;
}
Because when you finish typing CPF and press TAB, it counts as a character and changes to CNPJ mask.
Complete code:
<script type="text/javascript">
$(document).ready(function() {
$("#cpfcnpj").keydown(function(objEvent){
if (objEvent.keyCode == 9) { //tab pressed
return;
}
try {
$("#cpfcnpj").unmask();
} catch (e) {}
var size= $("#cpfcnpj").val().length;
if(size < 11){
$("#cpfcnpj").mask("999.999.999-99");
} else {
$("#cpfcnpj").mask("99.999.999/9999-99");
}
});
});
</script>
How can the cursor be focus on a specific input box on page load?
Is it posible to retain initial text value as well and place cursor at end of input?
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />
There are two parts to your question.
1) How to focus an input on page load?
You can just add the autofocus attribute to the input.
<input id="myinputbox" type="text" autofocus>
However, this might not be supported in all browsers, so we can use javascript.
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
2) How to place cursor at the end of the input text?
Here's a non-jQuery solution with some borrowed code from another SO answer.
function placeCursorAtEnd() {
if (this.setSelectionRange) {
// Double the length because Opera is inconsistent about
// whether a carriage return is one character or two.
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
// This might work for browsers without setSelectionRange support.
this.value = this.value;
}
if (this.nodeName === "TEXTAREA") {
// This will scroll a textarea to the bottom if needed
this.scrollTop = 999999;
}
};
window.onload = function() {
var input = document.getElementById("myinputbox");
if (obj.addEventListener) {
obj.addEventListener("focus", placeCursorAtEnd, false);
} else if (obj.attachEvent) {
obj.attachEvent('onfocus', placeCursorAtEnd);
}
input.focus();
}
Here's an example of how I would accomplish this with jQuery.
<input type="text" autofocus>
<script>
$(function() {
$("[autofocus]").on("focus", function() {
if (this.setSelectionRange) {
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
this.value = this.value;
}
this.scrollTop = 999999;
}).focus();
});
</script>
Just a heads up - you can now do this with HTML5 without JavaScript for browsers that support it:
<input type="text" autofocus>
You probably want to start with this and build onto it with JavaScript to provide a fallback for older browsers.
$(document).ready(function() {
$('#id').focus();
});
function focusOnMyInputBox(){
document.getElementById("myinputbox").focus();
}
<body onLoad="focusOnMyInputBox();">
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" onfocus="this.value = this.value;" value = "initial text">
A portable way of doing this is using a custom function (to handle browser differences) like this one.
Then setup a handler for the onload at the end of your <body> tag, as jessegavin wrote:
window.onload = function() {
document.getElementById("myinputbox").focus();
}
very simple one line solution:
<body onLoad="document.getElementById('myinputbox').focus();">
Working fine...
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
Try:
Javascript Pure:
[elem][n].style.visibility='visible';
[elem][n].focus();
Jquery:
[elem].filter(':visible').focus();
This is what works fine for me:
<form name="f" action="/search">
<input name="q" onfocus="fff=1" />
</form>
fff will be a global variable which name is absolutely irrelevant and which aim will be to stop the generic onload event to force focus in that input.
<body onload="if(!this.fff)document.f.q.focus();">
<!-- ... the rest of the page ... -->
</body>
From: http://webreflection.blogspot.com.br/2009/06/inputfocus-something-really-annoying.html
If you can't add to the BODY tag for some reason, you can add this AFTER the Form:
<SCRIPT type="text/javascript">
document.yourFormName.yourFieldName.focus();
</SCRIPT>
Add this to the top of your js
var input = $('#myinputbox');
input.focus();
Or to html
<script>
var input = $('#myinputbox');
input.focus();
</script>