JS function applies checkbox value not immediately for IE - javascript

Another one cross-browser issue.
JS logic:
if one specific check-box is checked,that dependent ones are checked automatically
and vice versa,if this check-box is unchecked ,that dependent unchecked also:
function changeStatusCheckBox(statusCheckbox) {
if (statusCheckbox.id == "id1") {
if (statusCheckbox.checked == true) {
document.getElementById("id2").checked = true;
document.getElementById("id3").checked = true;
}
else {
document.getElementById("id2").checked = false;
document.getElementById("id3").checked = false;
}
}
}
FF is OK - check/uncheck performed immediately.
IE7 check/uncheck works after clicked on some other browser area.
It looks like IE expects for additional blur behaviour.
JS called from this .jsf:
<h:selectBooleanCheckbox id="id1"
value="#{payment.searchByPaymentCriteria}" onchange="javascript:changeStatusCheckBox(this);"/>
What is your opinion?
Thank you for assistance.

Internet Explorer and some other browsers also works like this. The onchange event is called only when the blur occours and something changed. Text inputs and select combos are also like this.
The better way to do that with checkboxes, crossbrowser, is to bind it to the onclick event.
The onclick is called right after the mouseup event, so the checkbox status(checked or not) would be changed when the function is called.
Just do like
<h:selectBooleanCheckbox id="id1" value="#{payment.searchByPaymentCriteria}" onclick="javascript:changeStatusCheckBox(this);"/>

The way I like to this is to trap the click event only in IE, and blur/focus the checkbox. That will fire the change event in IE, and you can continue to use the change event for other browsers that support it. Click is not the same, and could introduce other issues. (Example utilizes $.browser from jQuery and assumes jQuery is included on the page.) Same example would work for radio buttons (substitute :radio for :checkbox).
function fixIEChangeEvent (){
if ($.browser.msie && $.browser.version < 9) {
$("input:checkbox").bind("click", function () {
this.blur();
this.focus();
});
}
}

Related

Click event fired twice on touch device

I have a checkbox in a sortable div where the click or changed event is triggered twice on touch devices but not on desktop (nor simulating touch on Firefox dev tools) for some obscure reason. The unwanted effect is the checkbox being toggled twice in a row leaving it at its original state. I mention the div is sortable because when they are made no longer sortable the checkbox works just fine. Here is the relevant part:
$sortable.sortable({
items: '.sortable',
cancel: 'input,textarea,button,select,option'
});
I have no idea why the sortable widget makes the click event be fired twice.
My attempts to handle this have been unsuccessful:
I've tried disabling the default behaviour of toggling a the checkbox and setting its value manually. However for some reason the checkbox won't be checked/unchecked. If I do it via console it does work:
// same with the "change" event
// the reason the event is bound to $sortable rather than the inputs themselves is that
// new sortable divs are added dynamically so otherwise they wouldn't have the event bound to them
$sortable.on('click', 'input[type="checkbox"]', function (e) {
e.stopImmediatePropagation();
// this does disable the default behaviour of checking/unchecking the box
e.preventDefault();
const $this = $(this);
// this doesn't check/uncheck the box at all, but setting a global variable to $this and doing it via console does work
$this.prop('checked', !$this.prop('checked'));
});
I have tried a more typical approach using a flag, however there seems to be some race condition (or whatever it's called because if I am not mistaken js is monothreaded) and the function is run twice anyway:
let checked = false;
$sortable.on('click', 'input[type="checkbox"]', function() {
if (checked) return;
// this is output twice, which is not what we are after
console.log('running');
checked = true;
// here ideally we would set the value of the checkbox
checked = false;
});
I have checked for any problematic events bound to the inputs using $._data($checkboxes[0], 'events') but other than a bootstrap tooltip (mouseover and mouseout events) and of course the change event there's nothing else fishy.
edit: Basically it seems that the sortable widget produces a separate click event when you click anywhere in the div or its children. That's the reason why click/change is fired twice.
My question is: how can I discriminate between the originator of the event so that if it's the sortable plugin the event can be ignored, while if it's the listener I set up the checkbox does change its value (and I perform any other actions I may want to perform when the checkbox is actually checked)?
try touchend and if it works for click as well use the following way , else separate it
$sortable.on("touchend click", 'input[type="checkbox"]', function(e) {
if(e.type == 'touchend'){
$(this).off('click');
// your function
}
});
else try this for both
let checked = false;
$sortable.on("touchend click", 'input[type="checkbox"]', function(e) {
if(e.type == "touchend") {
checked = true;
// your function
}
else if(e.type == "click" && !checked ) {
// your function
}
});

e.preventDefault() & return false not working in firefox

Chrome :
Following code is working in Chrome.
$('.links').click(function(e) {
if(e.which == 2) {
console.log(e.which); // prints 2
//e.preventDefault();
//e.stopPropagation();
return false;
}
});
Firefox :
Since above code doesn't catch middle button / mouse wheel click event in firefox, I tried following which is able to catch mouse wheel click event.
$('.links').mousedown(function(e) {
if(e.which == 2) {
console.log(e.which); // prints 2
//e.preventDefault();
//e.stopPropagation();
return false;
}
});
Above code prints 2. But return false; is not working.
When I replaced console.log with alert then it works. But I can't & don't want to use alerts.
I tried mouseup, mousewheel events also. But it didn't work.
I tried attachEvent also but, I got an error(attchEvent is not a function).
I am using below mentioned js files :
jQuery-1.10.2.min.js
jquery.easyui.min.js
jquery-ui.js
jquery.ui.core.js
You can refer below links for more clarity.
jsfiddle.net/nilamnaik1989/vntLyvd2/3
jsfiddle.net/nilamnaik1989/2Lq6mLdp
http://jsfiddle.net/nilamnaik1989/powjm7qf/
http://jsfiddle.net/nilamnaik1989/q6kLvL1p/
Following are some good links. But anyhow it doesn't solve my problem.
event.preventDefault() vs. return false
event.preventDefault() vs. return false (no jQuery)
http://www.markupjavascript.com/2013/10/event-bubbling-how-to-prevent-it.html
I need your valuable inputs.
All click default actions should be cancelable. That's one of the points of this important event. However, certain browsers have exceptions:
IE 5-8 won't prevent the default on text inputs and textareas.
IE9/10 & Opera incorrectly un-check radio buttons when you click on another radio in the same group. It correctly doesn't check the new radio.
IE 5-8, Firefox, & Opera won't prevent the default on select boxes.
Firefox & Chrome feel that one radio button must be checked. If all are unchecked they’ll check the first one you click on, even if the default is being prevented.
See Events - click, mousedown, mouseup, dblclick for some more information.
I had the same issue with firefox, related with
preventDefault();
Everything was working well in Safari, Chrome, Opera and even in IE9 (not kidding)
But, after a lot of reading, I saw that the site was using and old jquery version (1.10), then updated to the latest one (2.1.4) the action was canceled even in Firefox.
Another thing to consider is that I used a variable named "keyPressed" like:
var keyPressed = event.keyCode || event.which || event.charCode
So it was easy for each browser to recognize the key event.
Hope this help!
I have faced the similar problem in FF on middle click.
The following script fixed me the issue and it works fine in FF as well.
$(document).on('click', $(".content"), function(e) {
if(e.button==1) {
e.preventDefault();
return false;
}
})

After clicking on selected text, window selection is not giving updated range

After double click, selection range can be obtained correctly on onclick event but when I again click on the selected text then updated selection range should be returned by window selection but this is not happening. Can anybody tell me if this is a bug in javascript selection or they have made it this way. And what could be the solution to get the updated range apart from timer.
<div id="xyz" contenteditable="true">Hello world</div>
<span class="status">Selected text : </span>
javascript code :
function yourFunction() {
if (window.getSelection) {
var selectionRange = window.getSelection();
$('.status').text(selectionRange.toString());
}
}
$('#xyz').click(function () {
$('.status').text('Mouse click');
yourFunction();
})
Example here
You fiddle is working just fine. But, yes sometimes when you do selections in quick succession, then it fails to register the click.
The problem really lies in the way you have implemented it on click on the text input itself. A click event is generated when a mouseup follows a mousedown. A selection happens when you mousedown then drag and then mouseup.
If you separate out the selection retrieval then this problem won't occur.
See this updated fiddle: http://jsfiddle.net/zRr4s/21/
Here, the selection retrieval is donw on a button click, instead of the input itself.
i.e., instead of:
$('#xyz').click(function (e) { ...
using this:
$('#btn').click(function () { ...
where, btn is:
<input id="btn" type="button" value="get selection" />
Hope that helps.
Update:
If you insist on handling event only on the input, then listening mouseup would be better option:
See this fiddle: http://jsfiddle.net/zRr4s/22/
$('#xyz').on("mouseup", function (e) { ...
Update 2:
To handle your requirement of in-context click, you will have to first clear the selection. For this to happen you will have to handle mousedown. So, that will defeat your purpose of having only one handler. Anyway,
You updated fiddle: http://jsfiddle.net/zRr4s/29/
And, this is how you do it:
$('#xyz').on("mousedown", function () {
clearTheSelection();
});
Where clearTheSelection is another function:
function clearTheSelection() {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
The complete code for the above function taken from this answer: https://stackoverflow.com/a/3169849/1355315
Hope that completes all your problems.
The fiddle provided in the question works fine in Edge and IE11 but doesn't work in Chrome. I found a trick to make it work everywhere. Add the following event handler in addition to the click handler you already have:
$(document).on("selectionchange", function () {
yourFunction();
});
Some notes:
selectionchange is a document level event, you cannot bind it to specific element (but you can find out whether you need to handle it within the event handler)
Handling selectionchange without also handling click doesn't work well in Edge and IE11
According to MDN, browser support is good enough: https://developer.mozilla.org/en-US/docs/Web/API/Document/selectionchange_event

Difference of behaviour when clicking an "indeterminate" checkbox in HTML [duplicate]

Primer: An HTML checkbox can be set as indeterminate, which displays it as neither checked nor unchecked. Even in this indeterminate state, there is still an underlying boolean checked state.
When an indeterminate checkbox is clicked, it loses its indeterminate state. Depending on the browser (Firefox), it can additionally toggle the checked property.
This jsfiddle illustrates the situation. In Firefox, clicking either of the checkboxes once causes them to toggle their initial underlying checked state. In IE, the checked property is left alone for the first click.
I would like all browsers to behave the same, even if this means additional javascript. Unfortunately, the indeterminate property is set to false before the onclick handler (or onchange and jquery change) is called, so I can't detect whether it's called for a click on an indeterminate checkbox or not.
The mouseup and keyup (for spacebar toggle) events show the prior indeterminate state, but I'd rather not be that specific: it seems fragile.
I could maintain a separate property on the checkbox (data-indeterminate or similar), but I wanted to know if there's a simple solution I'm missing, and/or if other people are having similar issues.
If you would like to have an inderterminate checkbox which becomes checked on all browsers on click (or at least on IE, Chrome and FF5+), you need to initialise the checked attribute correctly, as shown here http://jsfiddle.net/K6nrT/6/. I have written the following functions to help you:
/// Gives a checkbox the inderminate state and the right
/// checked state so that it becomes checked on click
/// on click on IE, Chrome and Firefox 5+
function makeIndeterminate(checkbox)
{
checkbox.checked = getCheckedStateForIndeterminate();
checkbox.indeterminate = true;
}
and the interesting function which relies on feature detection:
/// Determine the checked state to give to a checkbox
/// with indeterminate state, so that it becomes checked
/// on click on IE, Chrome and Firefox 5+
function getCheckedStateForIndeterminate()
{
// Create a unchecked checkbox with indeterminate state
var test = document.createElement("input");
test.type = "checkbox";
test.checked = false;
test.indeterminate = true;
// Try to click the checkbox
var body = document.body;
body.appendChild(test); // Required to work on FF
test.click();
body.removeChild(test); // Required to work on FF
// Check if the checkbox is now checked and cache the result
if (test.checked)
{
getCheckedStateForIndeterminate = function () { return false; };
return false;
}
else
{
getCheckedStateForIndeterminate = function () { return true; };
return true;
}
}
No image tricks, no jQuery, no extra attributes and no event handling involved. This relies only on simple JavaScript initialisation (note that the "indeterminate" attribute cannot be set in the HTML markup, so JavaScript initialisation would have been required anyway).
This solved my problem
$(".checkbox").click(function(){
$(this).change();
});
I am not sure that will using function to set value for indeterminate checkboxes will be good solutions because:
you will have to change every place where you are using them,
if user submit form without clicking on check-boxes, value that
your backend will receive will be different depending of browser.
But I like clever way to determinate how browser works.
So you could check isCheckedAfterIndeterminate() instead usual window.navigator.userAgent.indexOf('Trident') >= 0 to see is it IE (or maybe other browser that works in unusual way).
So my solution will be:
/// Determine the checked state to give to a checkbox
/// with indeterminate state, so that it becomes checked
/// on click on IE, Chrome and Firefox 5+
function isCheckedAfterIndeterminate()
{
// Create a unchecked checkbox with indeterminate state
var test = document.createElement("input");
test.type = "checkbox";
test.checked = false;
test.indeterminate = true;
// Try to click the checkbox
var body = document.body;
body.appendChild(test); // Required to work on FF
test.click();
body.removeChild(test); // Required to work on FF
// Check if the checkbox is now checked and cache the result
if (test.checked) {
isCheckedAfterIndeterminate = function () { return false; };
return false;
} else {
isCheckedAfterIndeterminate = function () { return true; };
return true;
}
}
// Fix indeterminate checkbox behavoiur for some browsers.
if ( isCheckedAfterIndeterminate() ) {
$(function(){
$(document).on('mousedown', 'input', function(){
// Only fire the change event if the input is indeterminate.
if ( this.indeterminate ) {
this.indeterminate = false;
$(this).trigger('change');
}
});
});
}
Well make your own clickable image and use some java(script) to make it behave like that.
I doubt dough how many users would understand this state, so be carefull where you use it.

Jquery : how to trigger an event when the user clear a textbox

i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />

Categories

Resources