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.
Related
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 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>
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 :)
So im trying to show a div when one of the multiple checkboxes are clicked and it is working but when you unclick a checkbox it hides the div even when checkboxes are still clicked. I cant seem to figure out how to make it hide the div only when no checkboxes are left clicked.
<input type="checkbox" name="list[]" value="1" id="fldcheckbox" onclick="fnchecked(this.checked);">
<input type="checkbox" name="list[]" value="2" id="fldcheckbox" onclick="fnchecked(this.checked);">
<input type="checkbox" name="list[]" value="3" id="fldcheckbox" onclick="fnchecked(this.checked);">
<div id="ref_options" style="display:none;">
example
</div>
<script>
function fnchecked(blnchecked)
{
if(blnchecked)
{
document.getElementById("ref_options").style.display = "";
}else{
document.getElementById("ref_options").style.display = "none";
}
}
</script>
Use change event instead of click.
Actually you are hiding/displaying the div based on the checked value of each checkbox.
When just one checkbox is unchecked then you variable blnchecked become false, that makes div invisible.
You probably want this
function fnchecked(blnchecked) {
var checkboxs = document.getElementsByName("list[]");
var ischecked = false;
for (var i = 0, l = checkboxs.length; i < l; i++) {
if (checkboxs[i].checked) {
ischecked = true;
}
}
if (ischecked) {
document.getElementById("ref_options").style.display = "block";
} else {
document.getElementById("ref_options").style.display = "none";
}
Js Fiddle Demo
You can remove the function parameter as there is no use of it inside the function.
see this DEMO
html:
<input type="checkbox" name="list[]" value="1" id="fldcheckbox" onclick="fnchecked(this.checked?++c:--c);">
java script:
<script>
var c=0;
function fnchecked(c){
if(c>0){
document.getElementById("ref_options").style.display = "";
}else{
document.getElementById("ref_options").style.display = "none";
}
}
</script>
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.