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>
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'm rather new to js and i'd like to optimize my code.
I have a group of checkboxes and their boolean values are saved in an object for further calculations.
HTML:
<fieldset>
<input type="checkbox" id="checkbox1" onchange="checkbox1Changed()" value="checkbox1">
<input type="checkbox" id="checkbox2" onchange="checkbox2Changed()" value="checkbox2">
<input type="checkbox" id="checkbox3" onchange="checkbox3Changed()" value="checkbox3">
</fieldset>
JS:
//store values for further computation
var boxValues = {
box1: false,
box2: false,
box3: false,
}
//get checkboxvalues from view
var checkbox1 = document.getElementById("checkbox1");
var checkbox2 = document.getElementById("checkbox2");
var checkbox3 = document.getElementById("checkbox3");
//update values in boxValues
function checkbox1Changed() {
if (checkbox1.checked) {
boxValues.box1 = true;
} else {
boxValues.box1 = false;
}
}
function checkbox2Changed() {
if (checkbox2.checked) {
boxValues.box2 = true;
} else {
boxValues.box2 = false;
}
}
function checkbox3Changed() {
if (checkbox3.checked) {
boxValues.box3 = true;
} else {
boxValues.box3 = false;
}
}
Since i plan on having approximately 20 checkboxes in the view there would be a lot of repeating code.
Does anyone know a smarter way to do that?
Thanks in advance!
Vin
Add common class to all the checkboxes
Create an object for the values of all checkboxes
Bind event handler on the checkboxes using the common class
Update the status of clicked checkbox in event handler
Also, it is good practice to bind events in javascript instead of inline in the HTML.
var myObj = {
checkbox1: false,
checkbox2: false,
checkbox3: false
};
$('.myCheckbox').on('change', function() {
var thisId = $(this).attr('id');
myObj[thisId] = this.checked;
console.log(myObj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<fieldset>
<input type="checkbox" id="checkbox1" value="checkbox1" class="myCheckbox">
<input type="checkbox" id="checkbox2" value="checkbox2" class="myCheckbox">
<input type="checkbox" id="checkbox3" value="checkbox3" class="myCheckbox">
</fieldset>
You can bind the same function to every checkbox, and use the id of the checkbox as the key in your object:
function onCheckBoxChanged(e){
var sender = e.target;
boxValues[sender.id] = (sender.checked);
}
Playing around with this should save you a lot of typing :)
I have a dropdowncheckbox and the hiddenfield value.The hidden field values are 1,3,4,5.So I want to set dropdowncheckbox to be checked after postback in jquery for related hiddenfield values.How do I do that?
$(document).ready(function() {
var Statushdn = document.getElementById('<%= hdnSubCategoryId.ClientID%>').value;
var str_array = Statushdn.split(',');
var summar;
$.each($('#ContentPlaceHolder1_ddcbProductStockSubCategory_dv input[type=checkbox]:not(:checked)'), function() {
summar = $(this).val();
for (var i = 0; i < str_array.length; i++) {
if (str_array[i] == summar)
$(this).attr('checked', 'checked');
}
});
});
You can use localstorage to keep the values from checkboxes like:
$(':checkbox').on('change', function () {
//set the check value of checkbox
localStorage.setItem(this.id, this.checked);
});
$(':checkbox').each(function () {
//retrieve the checked value from the checkboxes and 'convert' it to bool
var status = localStorage.getItem(this.id) === "false" ? false : true;
$(this).prop("checked", status);
});
<input type="checkbox" id="chk1" />
<input type="checkbox" id="chk2" />
<input type="checkbox" id="chk3" />
<input type="checkbox" id="chk4" />
fiddle
References:
Window.localStorage
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.