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

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.

Related

Why does a checkbox always return the same value?

Edit3: Before more people keep downvoting this, please note this is not a duplicate question.
I'm working on a site that needs a table full of checkboxes and each one needs to be toggled on/off. Sometimes toggling one on needs to toggle others off and so on.
I did not build the base code, but since it was rather messy with all the logic going on, I decided to make some work like radios so we only have one base function to make much of the logic work.
I also have a function to enable/disable some checkboxes. It all works nicely, no problems at all.
But now there's another thing in play which is a text input. If a certain value is selected in it, some checkboxes automatically get turned on/off and locked in. The same base function is used to do this. But when a checkbox gets disabled with this, and then re-enabled, the following function keeps returning always true only for that checkbox:
$('input[type="checkbox"]').change(function() {
// Make checkboxes with names work like radios (radios can't be toggled off)
if ($(this).attr("name")) {
// Save clicked toggle value
var selected_toggle = $(this).attr('value');
// disable all and then toggle clicked one on
if ($('input[value="'+selected_toggle+'"]').prop("checked")) {
console.log("This is checked");
$('input:checkbox[name='+$(this).attr('name')+']').each(function() {
toggle_checkbox($(this).attr('value'), 'disabled');
});
toggle_checkbox(selected_toggle, 'enabled', 'on');
}
// Enable them all back if unchecking
else {
console.log("This is unchecked");
$('input:checkbox[name='+$(this).attr('name')+']').each(function() {
toggle_checkbox($(this).attr('value'), 'enabled');
});
$(this).parent().toggleClass("on");
}
}
else {
// Toggle them on or off
$(this).parent().toggleClass("on");
}
});
The obvious thing would be to say "something is different when locking/unlocking that checkbox", but it's all the same function and same way all other toggles get disabled, this is used from toggle_checkbox function:
function toggle_checkbox(toggle, value, on, lock) {
// Disable the toggle completely
if (value == 'disabled') {
$('input[value="'+toggle+'"]').attr('disabled', 'disabled');
$('input[value="'+toggle+'"]').parents('li').addClass('disabled');
$('input[value="'+toggle+'"]').parent().removeClass('on');
$('input[value="'+toggle+'"]').prop('checked', false);
}
// Enable a toggle back
if (value == 'enabled') {
$('input[value="'+toggle+'"]').parents('li').removeClass('disabled');
// Turn it on
if (on == 'on') {
$('input[value="'+toggle+'"]').parent().addClass('on');
$('input[value="'+toggle+'"]').prop('checked', true);
}
// Lock it on or remove disabled
if (lock == 'lock') {
$('input[value="'+toggle+'"]').attr('disabled', 'disabled');
}
else {
$('input[value="'+toggle+'"]').removeAttr('disabled');
}
}
}
When I remove the above code for name attributes, the checkbox works fine. Yet though every other checkbox returns Checked/unchecked properly, when clicking that specific un-disabled one, it always returns "this is checked".
I was using is(":checked") before, changing to prop made no difference.
Edit: As said in the comments, using prop or attr didn't make a difference. This is the code that is locking the checkbox that gets "stuck":
function set_hint_toggles(type, state) {
if (type == 'apples') { // Set when you select something with apples
toggle_checkbox('pears', 'disabled');
toggle_checkbox('apples', 'enabled', 'on', 'lock');
toggle_checkbox('oranges', 'disabled');
}
if (state == 'off') { // This is set when a reset button is pressed
var toggles_type = $('#hidden-input-with-value').val();
toggle_checkbox(toggles_type, 'enabled'); // This checkbox gets stuck, all others continue working
$('#text-input').removeAttr("disabled"); // Allows to type something again
}
}
Edit2: After trying Marvin answer I got a slighly different result that could help finding what's wrong:
This stuck checkbox has a "checked" and "disabled" state. When the reset button is clicked, disabled gets removed, but it remains checked (or should). When I tried to click the checkbox with the above code after reset, it was like it got re-checked once, and then kept stuck with checked.
Using [0].disabled = false, I can then keep toggling the checkbox on and off, but no js gets activated for it, and every click still returns checked.
Edit4: When attempting to use
toggle_checkbox(toggles_type, 'disabled');
toggle_checkbox(toggles_type, 'enabled');
In the code that makes the checkbox get stuck (set_hint_toggles(off) function above), it gets disabled only. Afterwards, this checkbox keeps returning always false instead of always true.
Theres a litle tip that you can use to improve your code.. Without a jsfiddle or some example, i'm afraid that i can't help you more than this. You should try using the DOM native api to set the disabled item
$('input[value="'+toggle+'"]')[0].disabled //returns if the element is disabled
$('input[value="'+toggle+'"]')[0].disabled = true //set element as disabled or not
The same works for the checked attribute.
$('input[value="'+toggle+'"]')[0].checked //returns if the element is checked
$('input[value="'+toggle+'"]')[0].checked = true //set element as checked or not
It truly was something wrong in the first block of code I posted. I'm now using this based off Adeneo's suggestion on changing the selectors and it's working perfectly:
// Search checkbox toggles
$('input[type="checkbox"]').change(function() {
// Make checkboxes with names work like radios (radios can't be toggled off)
if ($(this).attr("name")) {
if (this.checked) {
$('[name='+ this.name +']').each(function() {
toggle_disabled( this.value, 'disabled');
});
toggle_disabled( this.value, 'enabled', 'on');
}
else {
$('[name='+ this.name +']').each(function() {
toggle_disabled( this.value, 'enabled');
});
$(this).parent().toggleClass("on");
}
}
// Else if no name, just toggle on class
else {
$(this).parent().toggleClass("on");
}
});
I believe the problem was in the selector used for testing if the checkbox was on.
I'm also using prop on everything else now, but this did not change anything and does not seem like it had to do with the problem at all. The other suggestions also did not do anything.

How to call a function when default browser autocomplete list item selected [duplicate]

I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the keyup, change and click events.
The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither change nor click). Note that if you select from the autocomplete box and the blur the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .
See: http://jsfiddle.net/pYKKp/ (hopefully you have filled out a lot of forms in the past with an input named "email").
HTML:
<input name="email" />
<div id="whatever"><whatever></div>
CSS:
div {
float: right;
}
Script:
$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
I recommending using monitorEvents. It's a function provide by the javascript console in both web inspector and firebug that prints out all events that are generated by an element. Here's an example of how you'd use it:
monitorEvents($("input")[0]);
In your case, both Firefox and Opera generate an input event when the user selects an item from the autocomplete drop down. In IE7-8 a change event is produced after the user changes focus. The latest Chrome does generate a similar event.
A detailed browser compatibility chart can be found here:
https://developer.mozilla.org/en-US/docs/Web/Events/input
Here is an awesome solution.
$('html').bind('input', function() {
alert('test');
});
I tested with Chrome and Firefox and it will also work for other browsers.
I have tried a lot of events with many elements but only this is triggered when you select from autocomplete.
Hope it will save some one's time.
Add "blur". works in all browsers!
$("input").on('blur keyup change click', function () {
As Xavi explained, there's no a solution 100% cross-browser for that, so I created a trick on my own for that (5 steps to go on):
1. I need a couple of new arrays:
window.timeouts = new Array();
window.memo_values = new Array();
2. on focus on the input text I want to trigger (in your case "email", in my example "name") I set an Interval, for example using jQuery (not needed thought):
jQuery('#name').focus(function ()
{
var id = jQuery(this).attr('id');
window.timeouts[id] = setInterval('onChangeValue.call(document.getElementById("'+ id +'"), doSomething)', 500);
});
3. on blur I remove the interval: (always using jQuery not needed thought), and I verify if the value changed
jQuery('#name').blur(function ()
{
var id = jQuery(this).attr('id');
onChangeValue.call(document.getElementById(id), doSomething);
clearInterval(window.timeouts[id]);
delete window.timeouts[id];
});
4. Now, the main function which check changes is the following
function onChangeValue(callback)
{
if (window.memo_values[this.id] != this.value)
{
window.memo_values[this.id] = this.value;
if (callback instanceof Function)
{
callback.call(this);
}
else
{
eval( callback );
}
}
}
Important note: you can use "this" inside the above function, referring to your triggered input HTML element. An id must be specified in order to that function to work, and you can pass a function, or a function name or a string of command as a callback.
5. Finally you can do something when the input value is changed, even when a value is selected from a autocomplete dropdown list
function doSomething()
{
alert('got you! '+this.value);
}
Important note: again you use "this" inside the above function referring to the your triggered input HTML element.
WORKING FIDDLE!!!
I know it sounds complicated, but it isn't.
I prepared a working fiddle for you, the input to change is named "name" so if you ever entered your name in an online form you might have an autocomplete dropdown list of your browser to test.
Detecting autocomplete on form input with jQuery OR JAVASCRIPT
Using: Event input. To select (input or textarea) value suggestions
FOR EXAMPLE FOR JQUERY:
$(input).on('input', function() {
alert("Number selected ");
});
FOR EXAMPLE FOR JAVASCRIPT:
<input type="text" onInput="affiche(document.getElementById('something').text)" name="Somthing" />
This start ajax query ...
The only sure way is to use an interval.
Luca's answer is too complicated for me, so I created my own short version which hopefully will help someone (maybe even me from the future):
$input.on( 'focus', function(){
var intervalDuration = 1000, // ms
interval = setInterval( function(){
// do your tests here
// ..................
// when element loses focus, we stop checking:
if( ! $input.is( ':focus' ) ) clearInterval( interval );
}, intervalDuration );
} );
Tested on Chrome, Mozilla and even IE.
I've realised via monitorEvents that at least in Chrome the keyup event is fired before the autocomplete input event. On a normal keyboard input the sequence is keydown input keyup, so after the input.
What i did is then:
let myFun = ()=>{ ..do Something };
input.addEventListener('change', myFun );
//fallback in case change is not fired on autocomplete
let _k = null;
input.addEventListener( 'keydown', (e)=>_k=e.type );
input.addEventListener( 'keyup', (e)=>_k=e.type );
input.addEventListener( 'input', (e)=>{ if(_k === 'keyup') myFun();})
Needs to be checked with other browser, but that might be a way without intervals.
I don't think you need an event for this: this happens only once, and there is no good browser-wide support for this, as shown by #xavi 's answer.
Just add a function after loading the body that checks the fields once for any changes in the default value, or if it's just a matter of copying a certain value to another place, just copy it to make sure it is initialized properly.

Can jQuery check whether input content has changed?

Is it possible to bind javascript (jQuery is best) event to "change" form input value somehow?
I know about .change() method, but it does not trigger until you (the cursor) leave(s) the input field. I have also considered using .keyup() method but it reacts also on arrow keys and so on.
I need just trigger an action every time the text in the input changes, even if it's only one letter change.
There is a simple solution, which is the HTML5 input event. It's supported in current versions of all major browsers for <input type="text"> elements and there's a simple workaround for IE < 9. See the following answers for more details:
jQuery keyboard events
Catch only keypresses that change input?
Example (except IE < 9: see links above for workaround):
$("#your_id").on("input", function() {
alert("Change to " + this.value);
});
Yes, compare it to the value it was before it changed.
var previousValue = $("#elm").val();
$("#elm").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
alert("Value changed!");
}
});
Another option is to only trigger your changed function on certain keys. Use e.KeyCode to figure out what key was pressed.
You can also store the initial value in a data attribute and check it against the current value.
<input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" />
$("#id_someid").keyup(function() {
return $(this).val() == $(this).data().initial;
});
Would return true if the initial value has not changed.
function checkChange($this){
var value = $this.val();
var sv=$this.data("stored");
if(value!=sv)
$this.trigger("simpleChange");
}
$(document).ready(function(){
$(this).data("stored",$(this).val());
$("input").bind("keyup",function(e){
checkChange($(this));
});
$("input").bind("simpleChange",function(e){
alert("the value is chaneged");
});
});
here is the fiddle http://jsfiddle.net/Q9PqT/1/
You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):
$(document).ready(function() {
$("#fieldId").bind("keyup keydown keypress change blur", function() {
if ($(this).val() != jQuery.data(this, "lastvalue") {
alert("changed");
}
jQuery.data(this, "lastvalue", $(this).val());
});
});
This would work pretty good against a long list of items too. Using jQuery.data means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc") to track many fields.
UPDATE: Added blur to the bind list.
I had to use this kind of code for a scanner that pasted stuff into the field
$(document).ready(function() {
var tId,oldVal;
$("#fieldId").focus(function() {
oldVal = $("#fieldId").val();
tId=setInterval(function() {
var newVal = $("#fieldId").val();
if (oldVal!=newVal) oldVal=newVal;
someaction() },100);
});
$("#fieldId").blur(function(){ clearInterval(tId)});
});
Not tested...
I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier.
You can set events on a combination of key and mouse events, and onblur as well, to be sure. In that event, store the value of the input. In the next call, compare the current value with the lastly stored value. Only do your magic if it has actually changed.
To do this in a more or less clean way:
You can associate data with a DOM element (lookup api.jquery.com/jQuery.data ) So you can write a generic set of event handlers that are assigned to all elements in the form. Each event can pass the element it was triggered by to one generic function. That one function can add the old value to the data of the element. That way, you should be able to implement this as a generic piece of code that works on your whole form and every form you'll write from now on. :) And it will probably take no more than about 20 lines of code, I guess.
An example is in this fiddle: http://jsfiddle.net/zeEwX/
Since the user can go into the OS menu and select paste using their mouse, there is no safe event that will trigger this for you. The only way I found that always works is to have a setInterval that checks if the input value has changed:
var inp = $('#input'),
val = saved = inp.val(),
tid = setInterval(function() {
val = inp.val();
if ( saved != val ) {
console.log('#input has changed');
saved = val;
},50);
You can also set this up using a jQuery special event.

JS function applies checkbox value not immediately for IE

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

Checkbox onchange function

I have a page with a set of checkbox's, that I want to run a Javascript function on when there is a change (I have done something very similar with dropdown's - and that worked)
However with the checkbox's I have three problems:
my onChange event only runs "sometimes" (you have to change the focus between the different checkbox controls
when it does run it is returning the result of the previous checkbox (not the one just clicked on)
the jQuery always return the value true
Checkbox creation
<%= Html.CheckBox("sl-" + row.Id, value, new { onChange = "SuitabilityChecked("+row.Id+", "+key+")"})%>
Javascript
function SuitabilityChecked(providerId, parentRecordId) {
var params = {};
params.providerId = providerId;
params.parentRecordId = parentRecordId;
var value = $("#sl-" + providerId).val();
params.value = value;
$.getJSON("SuitabilityChecked", params, null);
};
Browsers are funny about radio buttons and check boxes and can delay the onchange until focus change. Try adding an onclick event to blur or call the change event directly.
Maybe something like this using jQuery Live (untested, off the top of my head):
$(':checkbox').live('click', function() { $(this).change(); });
What's happening:
Checkbox A clicked
Checkbox B clicked
Checkbox A has lost focus and fires onChange
Which makes it seem as if Checkbox B is returning the result of Checkbox A. If you were to press Tab after clicking Checkbox B in this scenario, you'd notice that its onChange would fire.

Categories

Resources