I have multiple check boxes with unique id, these are created dynamically and I need the check box clicked to be checked when the page is refreshed. I used the code below, but this checks all the check boxes upon refresh.
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
Any help would be appreciated.
$(document).ready(function () {
if (sessionStorage.getItem('checked-checkboxes') && $.parseJSON(sessionStorage.getItem('checked-checkboxes')).length !== 0)
{
var arrCheckedCheckboxes = $.parseJSON(sessionStorage.getItem('checked-checkboxes'));
//Convert checked checkboxes array to comma seprated id
$(arrCheckedCheckboxes.toString()).prop('checked', true);
}
$("input:checkbox").change(function () {
var arrCheckedCheckboxes = [];
// Get all checked checkboxes
$.each($("input:checkbox:checked"), function () {
arrCheckedCheckboxes.push("#" + $(this).attr('id'));
});
// Convert checked checkboxes array to JSON ans store it in session storage
sessionStorage.setItem('checked-checkboxes', JSON.stringify(arrCheckedCheckboxes));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Checkbox 1: <input type="checkbox" id="chk1"> <br>
Checkbox 2: <input type="checkbox" id="chk2"> <br>
Checkbox 3: <input type="checkbox" id="chk3"> <br>
Checkbox 4: <input type="checkbox" id="chk4"> <br>
Checkbox 5: <input type="checkbox" id="chk5"> <br>
Related
I have 4 checkboxes. I add values of them to an array on check. It looks like this.
Here are the four checkboxes I have.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
Once I check all four of them, the array becomes,
["degree", "pgd", "hnd", "advdip"]
When I uncheck a checkbox, I need to remove the value of it from the array according to its correct index number. I used splice() but it always removes the first index which is degree. I need to remove the value from the array according to its index number no matter which checkbox I unselect. Hope someone helps. Below is the code. Thanks in advance!
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = $(this).index();
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
You used the wrong way to find index in your code. If you used element index, it will avoid real index in your array and gives the wrong output. Check below code, it may be work for you requirement.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = selectedValues.indexOf(this.value);
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
Add change handler to the inputs and use jQuery map to get the values of the checked inputs.
var levels
$('#checkArray input').on('change', function () {
levels = $('#checkArray input:checked').map(function () {
return this.value
}).get()
console.log(levels)
}).eq(0).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
my approach was to add an event handler that reads all checked values when any of those inputs is clicked and empty the array before loging the response. no need to add any dependencies with this one
Hope this is what you are looking for
function getLevels() {
let checkboxContainer = document.getElementById("checkboxContainer");
let inputs = checkboxContainer.querySelectorAll("input");
let checked = [];
inputs.forEach( (input) => {
checked = [];
input.addEventListener( 'click', () => {
checked = [];
inputs.forEach( (e) => {
e.checked ? checked.push(e.value) : null;
})
console.log(checked);
});
});
}
getLevels();
<div id="checkboxContainer">
<input type="checkbox" value="degree" >
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</div>
I don't know if this is what you need, to show an array of the selected values, if you want you can call the function that calculates on the check.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
<button onclick="getLevels()">getLevels</button>
<script>
function getLevels() {
var levels = [];
$.each($("input:checked"), function() {
levels.push(($(this).val()));
});
console.log(levels);
}
getLevels();
</script>
I am trying to select one checkbox and disable all others. The problem is I am figure out how to do the reverse. Uncheck and enable all checkboxes.
Html:
This is a dynamic list of checkboxes
<input type="checkbox" id="mycheckbox1"/>
<input type="checkbox" id="mycheckbox2"/>
<input type="checkbox" id="mycheckbox3"/>
I have tried this:
var checkboxlist = $("input:checkbox");
$('.checkbox').on("change", function () {
var itemId = $(this).attr("id");
$.each(checkboxlist, function (index, value) {
var id = $(value).attr("id");
if (!(itemId === id)) {
$(value).attr("disabled", "true");
}
});
})
Much simpler to use not() inside event handler to target all the others.
Use the checked state of current checkbox to determine disabled state
$(':checkbox').change(function(){
// "this" is current checkbox
$(':checkbox').not(this).prop('disabled', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="mycheckbox1"/>
<input type="checkbox" id="mycheckbox2"/>
<input type="checkbox" id="mycheckbox3"/>
Sounds like for what you are trying to achieve a radio button list may be more appropriate.
<input type="radio" name="myRadio" value="myRadio1"/>
<input type="radio" name="myRadio" value="myRadio2"/>
<input type="radio" name="myRadio" value="myRadio3"/>
var checkboxlist = $("input:checkbox");
$('.checkbox').on("change", function () {
var itemId = $(this).attr("id");
if ($(this).is(':checked')) {
$.each(checkboxlist, function (index, value) {
var id = $(value).attr("id");
if (!(itemId === id)) {
$(value).attr("disabled", "true");
}
});
} else {
$.each(checkboxlist, function (index, value) {
var id = $(value).attr("id");
if (!(itemId === id)) {
$(value).attr("disabled", "false");
}
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a form with checkboxes. The javascript function allPosPlayersCheckboxes utilizes a "Check All" Checkbox that controls the others. The other functions (getPosAllFilterOptions & getPosPlayersFilterOptions) push the "name" properties into an array. This all is triggered when anything is changed on the form.
Suppose that all checkboxes are unchecked. If the user checks the "nonP_all" checkbox, it will automatically check the other checkboxes with class="nonP". Unfortunately, when the "name" properties are pushed into the array, it will not include any with class="nonP".
I"m unsure why they are not included in the array. Are the functions (getPosAllFilterOptions & getPosPlayersFilterOptions) not waiting for allPosPlayersCheckboxes to complete? Is there a way to have the secondary checkboxes included in the arrays? Thanks for any help!
<form id="formFilter">
<h2>Filter options</h2>
<div>
<input type="checkbox" id="nonP_all" class="Pos_all" name="nonP" checked="checked">
<label for="nonP">Position Players</label>
<input type="checkbox" id="C" class="nonP" checked="checked" name="C">
<label for="C">C</label>
<input type="checkbox" id="1B" class="nonP" checked="checked" name="1B">
<label for="1B">1B</label>
<input type="checkbox" id="2B" class="nonP" checked="checked" name="2B">
<label for="2B">2B</label>
<input type="checkbox" id="3B" class="nonP" checked="checked" name="3B">
<label for="3B">3B</label>
<input type="checkbox" id="SS" class="nonP" checked="checked" name="SS">
<label for="SS">SS</label>
<input type="checkbox" id="LF" class="nonP" checked="checked" name="LF">
<label for="LF">LF</label>
<input type="checkbox" id="CF" class="nonP" checked="checked" name="CF">
<label for="CF">CF</label>
<input type="checkbox" id="RF" class="nonP" checked="checked" name="RF">
<label for="RF">RF</label>
<input type="checkbox" id="DH" class="nonP" checked="checked" name="DH">
<label for="DH">DH</label>
</div>
function allPosPlayersCheckboxes(){
$("#nonP_all").click(function(){ // When it is clicked....
$('.nonP').prop('checked', this.checked); // Sets all to reflect "All"
});
$(".nonP").click(function(){ // When any are clicked....
if($(".nonP").length == $(".nonP:checked").length){ // If all are checked...
$("#nonP_all").prop("checked", true); // Sets "All" to "checked"
}else{
$("#nonP_all").prop("checked", false); // Sets "All" to "unchecked"
}
});
};
function getPosAllFilterOptions(){
var pos_all_opts = new Array();
$(".Pos_all:checked").each(function(){
pos_all_opts.push($(this).attr('name')); // places names into array
});
return pos_all_opts;
}
function getPosPlayersFilterOptions(){
var nonP_opts = new Array();
$(".nonP:checked").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
return nonP_opts;
}
var $formFilter = $("#formFilter");
$formFilter.change(function(){
allPosPlayersCheckboxes();
var pos_all_opts = getPosAllFilterOptions();
var nonP_opts = getPosPlayersFilterOptions();
console.log("pos_all_opts = " + pos_all_opts);
console.log("nonP_opts = " + nonP_opts);
updateQuery(pos_all_opts, nonP_opts);
});
updateQuery();
The reason that you are having an issue is because the checking of the boxes event is being caught at the form change event handler, and the code that checks and unchecks all of the other boxes hasn't executed yet. As a result when you call your functions, the count for checked boxes is 0. This also happens when you uncheck one of the position checkboxes, eventually the pos_all_opts variable gets out of sync and is incorrect as well.
These click handlers don't need to be in a function. They are handlers that are hooked into the behavior of your checkboxes.
$("#nonP_all").click(function(){ // When it is clicked....
$('.nonP').prop('checked', this.checked); // Sets all to reflect "All"
});
$(".nonP").click(function(){ // When any are clicked....
if($(".nonP").length == $(".nonP:checked").length){ // If all are checked...
$("#nonP_all").prop("checked", true); // Sets "All" to "checked"
}else{
$("#nonP_all").prop("checked", false); // Sets "All" to "unchecked"
}
});
This is probably a little less than ideal, but it works. The code that was in the functions to build the arrays has been moved into the change handler for the form.
$("#formFilter").change(function(event){
var pos_all_opts = [];
var nonP_opts = [];
if(event.target === $("#nonP_all")[0] && event.target.checked) {
pos_all_opts = 'nonP';
$(".nonP").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
} else if(event.target === $("#nonP_all")[0] && !event.target.checked) {
pos_all_opts = [];
nonP_opts = [];
} else if(event.target !== $("#nonP_all")[0] && $(".nonP:checked").length === 9) {
pos_all_opts = 'nonP';
$(".nonP").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
} else {
pos_all_opts = [];
$(".nonP:checked").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
}
console.log("pos_all_opts = " + pos_all_opts);
console.log("nonP_opts = " + nonP_opts);
updateQuery(pos_all_opts, nonP_opts);
});
updateQuery();
Fiddle for reference
I have two checkboxes with different names:
<input type="checkbox" name="checkbox1" value="checkbox1">
<input type="checkbox" name="checkbox2" value="checkbox2">
I'd like to implement code where when checkbox1 is checked, checkbox2 is disabled and when checkbox2 is checked, checkbox1 is disabled. When it's unchecked, it should enable the other back as well.
How can I achieve with jQuery or JavaScript?
Firstly, I'm assuming the work you want to do cannot be done via Radio Buttons because that's the obvious choice here. In case it can, here's a few links for that:
http://wiki.answers.com/Q/What_are_the_differences_between_radio_buttons_and_checkboxes
http://www.w3schools.com/html/tryit.asp?filename=tryhtml_radio
Checkbox 1: <input id="checkbox1" type="checkbox" onchange="onCheckboxChanged();"/>
Checkbox 2: <input id="checkbox2" type="checkbox" onchange="onCheckboxChanged();"/>
<script type="text/javascript">
//Initialize checkboxes
onCheckboxChanged();
</script>
Js:
var onCheckboxChanged = function(checkbox){
var checkbox1 = document.getElementById('checkbox1');
var checkbox2 = document.getElementById('checkbox2');
if(checkbox1.checked){
checkbox2.disabled = true;
}
else {
checkbox2.disabled = false;
}
};
try this code,
html,
<input type="checkbox" name="checkbox1" value="checkbox1"/>
<input type="checkbox" name="checkbox2" value="checkbox2"/>
javascript,
$('[type="checkbox"]').click(function() {
if ($(this).is(":checked")) {
$('[type="checkbox"]').not(this).attr('disabled', 'disabled');
} else {
$('[type="checkbox"]').not(this).removeAttr('disabled');
}
});
demo
http://jsfiddle.net/rsxXd/
here is jquery example http://jsfiddle.net/XnQzQ/
$('input[name=checkbox1]').click(function() {
if($('input[name=checkbox1]').is(':checked'))
{
$('input[name=checkbox2]').attr("disabled", "disabled")
}
else
{
$('input[name=checkbox2]').removeAttr( "disabled");
}
});
$('input[name=checkbox2]').click(function() {
if($('input[name=checkbox2]').is(':checked'))
{
$('input[name=checkbox1]').attr("disabled", "disabled")
}
else
{
$('input[name=checkbox1]').removeAttr( "disabled");
}
});
Avoid the overkill of jQuery and just use pure JavaScript.
HTML:
<input type="checkbox" id="checkbox1" value="checkbox1" onchange="checker()" />
<input type="checkbox" id="checkbox2" value="checkbox2" onchange="checker()" />
JavaScript:
function checker() {
var checkbox1 = document.getElementById('checkbox1');
var checkbox2 = document.getElementById('checkbox2');
checkbox1.disabled = checkbox2.checked;
checkbox2.disabled = checkbox1.checked;
}
Demo: http://jsfiddle.net/fEpWJ/
Simple with jQuery:
$(document).ready(function() {
var $cbs = $('input[type="checkbox"][name^="checkbox"]').click(function() {
$cbs.not(this).prop('disabled', this.checked);
});
});
Demo: http://jsfiddle.net/j6Jpz/
Though if the idea is to prevent both checkboxes being checked at the same time I'd suggest it is nicer for the user if you leave both enabled but when one is checked automatically uncheck the other:
$(document).ready(function() {
var $cbs = $('input[type="checkbox"][name^="checkbox"]').click(function() {
if (this.checked) $cbs.not(this).prop('checked', false);
});
});
Demo: http://jsfiddle.net/j6Jpz/1/
Note: the selector I've used, 'input[type="checkbox"][name^="checkbox"]', says to find all inputs of type checkbox with a name that starts with "checkbox". This could be simplified to 'input.someClass' if you gave a common class, class="someClass", to the inputs in question.
Note also that either version of my code will automatically handle larger groups of checkboxes.
I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.