I am trying to keep checkboxes checked on refresh with localStorage. All modern browsers do the job except IE11 (and lower)
Fiddle:
http://jsfiddle.net/usme91gk/
(function() {
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
console.log(oldVal);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function() {
localStorage.setItem(storageId, this.checked);
});
}
})();
Does anyone know if there's a way to somehow adapt this to IE? Or maybe you know a script that keeps checkboxes checked on refresh in all browsers? (Doesn't matter if it's in javascript or jquery). Any help is appreciated.
I use jstorage when I need localstorage. It has some added features like TTL (time to live).
http://www.jstorage.info
Related
I have a radio button which by default comes checked when the page loads ,and user can un_check if he want by single click but its not working in single click .. after three clicks the radio button un_checked.
Please see
JSFIDDLE . in the code the radio button with value 7 comes with checked by default , I can be able to un_check by clicking three times on it.is there any way to un_check it by just single click .Any help is appreciated.
Thank you.
<td style="padding-right:0px;"><input type="radio" name="TEST" onclick=" var allRadios = document.getElementsByName('TEST'); var booRadio; var x = 0; for(x = 0; x < allRadios.length; x++){ allRadios[x].onclick = function() { if (booRadio == this) { this.checked = false; booRadio = null; }else{ booRadio = this; } }; }" value="7" CHECKED> 7</td>
A JQuery solution, if you assing a class radioClass to your radio buttons:
(function () {
$('.radioClass').on('mouseup', function (e) {
var xRadioB = this;
if ($(xRadioB).is(':checked')) {
setTimeout(function () {
$(xRadioB).prop('checked', false);
}, 5);
}
});
})();
JSfiddle Example: https://jsfiddle.net/nfed1f7c/
First of all, I hope this is just for a test and that you will not embed events in your HTML as this will become very hard to manage, very quickly. I've manage to get a version working with some improve JavaScript. While I did not play with this for too long, I suspect there are better ways but that's a good first draft to get the results you desire: https://jsfiddle.net/0kyyfvy6/5/
var radioElements = document.querySelectorAll('input[type=radio]');
for (var iterator = 0; iterator < radioElements.length; iterator++) {
var radioElement = radioElements[iterator];
radioElement.addEventListener('mousedown', function (event) {
if (event.currentTarget.checked) {
var radioElement = event.currentTarget;
setTimeout(function () {
radioElement.checked = '';
}, 100);
}
})
}
I tried to have event.stopImmediatePropagation() and so on instead of the setTimeout but for some reasons it did not work. This seems relatively safe to implement depending on your use case.
I am trying to achieve something and I can't find/decide what is the best way to do it, so i'm going to ask if somebody did this before or if select2 has something built in in order to achieve what I want.
Heres the thing: I have a number of select (multiple) elements in my DOM, lets say 5, all share the same options, but, If one of the selects has an option selected, I want the others to hide/remove/avoid being selected, I would like to constrain all selects in order to avoid having the same value selected in 2 different selects. I am not asking for a full code solution, I just need to know if someone already did it (if yes, would be nice to get it shared in order for future developers that stumble upon this can see the solution), or if select2 has the functionallity.
What I have done so far is:
$('.constrainedSelect').each(function(i, select) {
var selectedValue = $(select).select2("val");
var options = $('#allOptions').find('option').clone();
if (selectedValue.length !== 0) {
options.each(function(i, option) {
if($(select).find('option[value="' + $(option).val() + '"]').length !== 1) {
$(select).append(option);
}
});
} else {
options.push($("<option />", {value: e.choice.id.trim(), text: e.choice.text.trim()})[0]);
$(select).html(options);
}
});
But thats just a concept and its really buggy.
The version of select2 i'm using (and need to use, no time to change it in production yet) is Version: 3.5.2 Timestamp: Sat Nov 1 14:43:36 EDT 2014
Thanks in advance!
I have found a nice way to do this, if anyone was wondering how, I think this is a good approach but I would like to see comments and if somebody wants to improve my answer, feel free to copy the code and paste it in a separate answer, if the approach gets better I will accept that answer. Thanks guys for the help.
var $selects = $(".constrainedSelects");
$selects.on('change', function(e) {
var selectedValues = $(this).select2('val');
for (var i = 0; i < selectedValues.length; i++) {
$selects.not(this).find("option[value='" + selectedValues[i] + "']").attr('disabled', true);
}
});
$selects.on('select2-removed', function(e) {
$selects.find("option[value='" + e.val + "']").attr('disabled', false);
});
Here is a fiddle to show the result: http://jsfiddle.net/rv38f0v6/
Please See if this helps! this is a jquery validation method to avoid same values in different select boxes.
$.validator.addMethod("valOption", function(value, element) {
var curValue,
allElems,
counter,
totalCount = 0;
curValue = value;
allElems = $('#myPage select');
for (counter = 0; counter < allElems.length; counter = counter + 1) {
if (curValue === allElems.eq(counter).val()) {
totalCount = totalCount + 1;
}
}
if (totalCount === 1) {
return this.optional(element) || (true);
} else {
return (false);
}
}, "Please select different option");
$(document).on('change', '.constrainedSelect', function() {
var changedSelect = $(this);
$(".constrainedSelect").not(changedSelect).select2("val", "").select2("enable", false)
});
I think something like this event listener would take care of it. It makes sure the val of all the others are empty and then disables them so they cannot be selected from.
How about this instead:
Working Fiddle
//setup trackign array and block duplicate selections
var selectedIds = [];
$(document).on('select2-selecting', '.constrainedSelect', function(event) {
var idx = $.inArray(event.val, selectedIds);
if(idx === -1) {
selectedIds.push(event.val);
} else {
event.preventDefault();
}
});
//remove selected item from our tracking array
$(document).on('select2-removed', '.constrainedSelect', function(event) {
var idx = $.inArray(event.val, selectedIds);
selectedIds.splice(idx,1);
});
I need to toggle all buttons with a single function. Function needs to toggle all checkboxes in the document as my checkboxes are freestanding and not part of a form.
I currently have this, but it is not working properly. I get syntax error: syntax error in my firefox console.
checked=false;
function checkedAll() {
var c = new Array();
c = doc.getElementsByTagName('input');
if (checked == false){
checked = true;
}else{
checked = false;
}
for (var i = 0; i < c.length; i++){
if (c[i].type == 'checkbox'){
c[i].checked = checked;
}
}
}
How can I fix my code?
Thanks
Two main items to refactor. First, instead of doc it must be document. Second instead of relying on a global just pass in a boolean to determine whether or not to check the checkboxes.
function checkedAll(isChecked) {
var c = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < c.length; i++){
c[i].checked = isChecked;
}
}
JS Fiddle: http://jsfiddle.net/Jvnfm/107/
You can alternatively perform the following for each checkbox element:
c[i].click();
This version will trigger any associated event handlers associated with that element.
I have a jquery function that shows/hides spans that look like "tips" when I click an input field on a form.
The function works great on FirfFox,Chrome,IE(!) :) , etc. But not at all on webkit based browsers aka Safari and Android (tested)
$(function(prepareInputsForHints) {
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++){
(function(i) {
// Let the code cleane
var span = inputs[i].nextElementSibling;
if(span instanceof HTMLSpanElement) {
if(span.className == "hint") {
span.onmouseover = function() { this.isOver = true; }
span.onmouseout = function() { this.isOver = false; if(!inputs[i].isFocus) inputs[i].onblur(); }
// the span exists! on focus, show the hint
inputs[i].onfocus = function () {
this.isFocus = true;
span.style.display = "inline";
}
// when the cursor moves away from the field, hide the hint
inputs[i].onblur = function () {
this.isFocus = false;
if(!span.isOver) span.style.display = "none";
}
}
}
})(i);
}
});
Also, for your convenience i provide you with http://jsfiddle.net/eZnYY/1/
Try to replace you code line:
if(span instanceof HTMLSpanElement) {
with next:
if(span && span.tagName.toUpperCase()==="SPAN") {
http://jsfiddle.net/eZnYY/3/ Checked on desktop Safary and Android browser (emulator)
You should use the jQuery methods to ensure cross browser compatibility (your question has the jQuery Tag).
This is pure javascript. Convert your code to jQuery, use the jQuery events and set the css.
For example:
your code
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++){ .. }
jQuery
$("input").each(function() { ... });
What I don't understand is, if you're using jquery, why are you not leveraging it in your function? I assure you that if you were to use jquery to attach the events, they will work in webkit and all other browsers.
I have the following code which is working fine in firefox but ie just doesn't want to know:
$("#termsandconditionscontinue").attr("disabled", "disabled");
$("#agreeTandC").click(function() {
var checked_status = this.checked;
if (checked_status == true) {
$("#termsandconditionscontinue").removeAttr("disabled");
}
else {
$("#termsandconditionscontinue").attr("disabled", "disabled");
}
});
Here is the example: http://jsfiddle.net/zidski/LXGMu/
The problem can lie in
var checked_status = this.checked;
Change it to:
var checked_status = $(this).attr("checked");
to make sure you use proper jQuery object which is cross browser compatible.