Uncheck a checkbox if another checked with javascript - javascript

I have two checkbox fields. Using Javascript, I would like to make sure only one checkbox can be ticked. (e.g if one checkbox1 is ticked, if checkbox2 is ticked, checkbox1 will untick)
<input name="fries" type="checkbox" disabled="disabled" id="opt1"/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled"/>
I would also like to have a radio button beneath, if this is clicked, I would like both checkboxes to be unticked.
<input type="radio" name="o1" id="hotdog" onchange="setFries();"/>
Would the best way to do this be by writing a function, or could I use onclick statements?

Well you should use radio buttons, but some people like the look of checkboxes, so this should take care of it. I've added a common class to your inputs:
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo: http://jsfiddle.net/5uUjj/

Also based on tymeJV's answer above, if you want to only deactivate the other checkbox when one is clicked you can do this:
function cbChange(obj) {
var instate=(obj.checked);
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
if(instate)obj.checked = true;
}
tymeJV's function does not let you have both unticked - this does.
(yes, weird but true.. sometimes there's a semantic reason why you want two tickboxes not radio buttons)

Hope this helps:
function setFries(){
var hotdog= document.getElementById("hotdog");
var opt1= document.getElementById("opt1");
var opt2 = document.getElementById("opt2");
if(hotdog.checked){
opt1.checked = false;
opt2.checked = false;
}else if(opt1.checked){
opt2.checked = false;
}else if(opt2.checked){
opt1.checked = false;
}
}

<input type="checkbox" name="fries" id="opt1" disabled="disabled" onclick="setFries(this);/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled" onclick="setFries(this);/>
<input type="radio" name="o1" id="hotdog" onclick="setFries(this);"/>
Note that I am using onclick event:
function setFries(obj){
var fries = document.getElementsByName('fries');
if(obj.id =='hotdog') //Or check for obj.type == 'radio'
{
for(var i=0; i<fries.length; i++)
fries[i].checked = true;
}
else{
for(var i=0; i<fries.length; i++){
if(fries[i].id != obj.id){
fries[i].checked = !obj.checked;
break;
}
}
}
}

The simplest way I found for this was to not use any sort of code at all. I triggered an actions in the check box properties.
1. mouse up to reset a form. I then unselected (for reset) all of my fields accept for my desired check boxes. I then did the same thing for my other check box to go the other way. You can basically turn the check boxes into toggles or have any sort of crazy pattern you want.

Related

Toggle Available Input/Radio with JS

I am trying to create a user input form that will disable/enable inputs depending on a prior input.
var test = document.getElementById("type");
console.log(test.value);
if (test.value == 'Limited') {
console.log('should be disabled');
var radios = document.getElementById("disableme");
for (var i = 0, iLen = radios.length; i < iLen; i++) {
radios[i].disabled = true;
}
}
function toggle() {
if (test.value == 'Limited') {
console.log('should be disabled');
var radios = document.getElementById("disableme");
for (var i = 0, iLen = radios.length; i < iLen; i++) {
radios[i].disabled = true;
}
} else if (test.vlaue !== 'Limited') {
console.log('should be enabled');
var radios = document.getElementById("disableme");
for (var i = 0, iLen = radios.length; i < iLen; i++) {
radios[i].disabled = false;
}
}
}
<select id="type" name="type" placeholder="" style="width: 300px" onchange="toggle()">
<option>Administrator
<option>Elevated
<option selected="selected">Limited
</select>
<form name="disableme" id="disableme">
Alerts & Messages : Yes <input type="radio" name="alert" id="alert" value='1'> No <input type="radio" name="alert" id="alert" checked="checked" value='0'>
</form>
Here is what my page currently looks like upon load:
With the limited option selected, I want both radio buttons to be disabled and the no radio button checked. If the user selects Administrator or Elevated I want those radio buttons enabled. I have made it this far.
My only issue now is that when I switch back to limited, having checked the yes radio button, the yes will remain checked while the radio buttons are disabled.
You will see my radio buttons have the same name/id. This was done to prevent both being selected at the same time.
In your current code, radios always refers to a form element. While in your case the only elements in that form are the radio buttons, assuming that to be the case is risky. Someone else might come along and add a button and then your button starts getting disabled and everyone freaks out.
Instead, just target the radio buttons. In the code below, I've targeted them by name, since that is shared among the radio buttons I think you want to target.
(I should note that, semantically, all form elements (including select elements) should belong to a form in order to aid submission. If you're not submitting the form to a server, this is less of a constraint.)
In any case, I've simplified the code a bit to only require a single loop over the radio buttons; if the selected item is "Limited", it sets the radios to disabled, and sets the "No" item to checked. If the selected item is not "Limited" it enables the radios and leaves the checked state alone.
var test = document.getElementById("type");
function toggle() {
console.log(test.value);
var radios = document.querySelectorAll('input[name="alert"]');
for (var i = 0, iLen = radios.length; i < iLen; i++) {
radios[i].disabled = test.value == 'Limited';
if (test.value == 'Limited') {
radios[i].checked = radios[i].value === '0';
}
}
}
toggle();
<select id="type" name="type" placeholder="" style="width: 300px" onchange="toggle()">
<option>Administrator</option>
<option>Elevated</option>
<option selected="selected">Limited</option>
</select>
<form name="disableme" id="disableme">
Alerts & Messages : Yes <input type="radio" name="alert" id="alert" value='1'> No <input type="radio" name="alert" id="alert" checked="checked" value='0'>
</form>

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

JS: uncheck box when another is checked but also uncheck itself if checked

I have three checkboxes. I am already using a piece of code I found here to uncheck the other two when one is checked.
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
I use this inside the checkbox to toggle the state: onchange="cbChange(this)".
However, I also need to provide for a situation where I don't want any of the boxes ticked. While I can do this by adding a separate button or checkbox, I wanted to know if the above code can be modified or another function added that will allow to untick the already ticked box by an onclick event.
I tried adding this function (again found here) but it won't work:
function cbUncheck(obj)
{
if (obj.checked == false)
{
document.getElementByClassName("cb").checked = false;
}
}
I use this in the checkbox code: onclick="cbUncheck(this);"
Suggestions welcome!
Thanks!
you need to check first checkbox checked or not..
if checkbox is not checked then dont need to do anything
otherwise uncheck other checkboxes
<input id="chk1" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk1" >1</label>
<input id="chk2" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk2" >1</label>
<input id="chk3" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk3" >1</label>
javascript
function cbChange(obj) {
if(obj.checked)
{
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
}
JS BIN JSBIN EXAMPLE
You can use radio buttons so that only one can be selected (no script required for that). Then if some other condition occurs, clear both (below uses a button as an example):
<form>
<input type="radio" name="foo" value="0">zero<br>
<input type="radio" name="foo" value="1">one<br>
<button type="button" onclick="clearRadios(this.form.foo)">Clear radios</button>
</form>
And the function:
function clearRadios(radioGroup) {
for (var i=0; i<radioGroup.length; i++) {
radioGroup[i].checked = false;
}
}
If you don't want users to check the radios at all, disable them.
This below code simply give solutions to what you need.
this.scan=function(index)
{
if( this.boxGroup[ index ].checked )
for(var i=0, g=this.boxGroup, len=g.length; i<len; i++)
if( i != index )
g[i].checked = false;
}
for working demo see jsfiddle

How to change the style of a radio button with javascript when clicked

I have an order form that has three sets of radio button options. Ultimately, I would like to have the text of the radio button in each group change to bold and red when it is clicked. However, I'm not having any luck just changing the color of even one group. Below is the loop I was using to try to change one group of radio buttons. My logic was to go through the group of radio buttons and if one of them were clicked it would change the style of the text. What am I doing wrong with this function?
function highlight() {
var radios = document.getElementsByName('cases');
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked == true) {
return document.getElementByName.style.color = 'red';
}
}
}
This is one group of radio buttons in my code. The other two groups are similar:
<input id="case1" type="radio" name="cases" value="500.00" onclick="highlight()"/> Desktop Case ($500.00) </br>
<input id="case2" type="radio" name="cases" value="600.00" onclick="highlight()"/> Mini-Tower Case ($600.00) </br>
<input id="case3" type="radio" name="cases" value="700.00" onclick="highlight()"/> Full-Tower Case ($700.00) </br>
Any help would be greatly appreciated.
If you amend your code, and wrap the text in a label element and, incidentally, you can't change the color or font-weight properties of text unless it's wrapped in an element, and that would have to be a separate element for each string of text you want to affect :
<input id="case1" type="radio" name="cases" value="500.00" onclick="highlight()"/><label for="case1">Desktop Case ($500.00)</label>
<input id="case2" type="radio" name="cases" value="600.00" onclick="highlight()"/><label for="case2">Mini-Tower Case ($600.00)</label>
<input id="case3" type="radio" name="cases" value="700.00" onclick="highlight()"/> <label for="case3">Full-Tower Case ($700.00)</label>
You can achieve this with just CSS:
input[type=radio]:checked + label {
color: red;
font-weight: bold;
}
JS Fiddle demo.
Incidentally, to use plain JavaScript I'd suggest:
function choiceHighlight(radio){
var groupName = radio.name,
group = document.getElementsByName(groupName);
for (var i = 0, len = group.length; i < len; i++){
group[i].nextSibling.className = group[i].checked ? 'chosen' : 'unchosen';
}
}
var radios = document.getElementsByName('cases');
for (var i = 0, len = radios.length; i < len; i++){
radios[i].addEventListener('change', function(){
choiceHighlight(this);
});
}
JS Fiddle demo.
Your return statement looks off:
return document.getElementByName.style.color = 'red';
Also note that you've attempted to give the radio inputs a color of red, but they cannot be styled in this way. The text that you have next to the inputs is not part of the input itself.
Here's a simplified script that gets you the input values onchange (not onselect). You should be able to use this as a better starting point: http://jsfiddle.net/rWp6E/
var radios = document.getElementsByName('cases');
for (var i = 0; i < radios.length; i++) {
radios[i].onchange = function () {
alert(this.value);
}
}
getElementByName isn't valid Javascript. A better way to do this would be to use the onCheckedChanged event to change your style:
<input id="case1" type="radio" name="cases" oncheckedchanged="highlight(this)" value="500.00"/>
<script type="text/javascript">
function highlight(e) {
if(e.checked == true)
{e.style.color = "red"}
else
{e.style.color = "some other color"}
}
Note that you will actually have to change the style of the label if you want to change the color of the text.
There is also a :checked selector in CSS3 (as someone else mentioned above), however it will not work in some older browsers, namely IE8 and earlier.

Select all checkbox functionality in classic asp

I have a select all checkbox followed by individual checkboxes corresponding to each record which comes from database.
How do I implement a javascript function such that when a person checks Select all,all the checkboxes get selected and vice versa.
first give an id to your select all check box say "selectall" and give a class to all other check boxes as allcheck and try using this code .
$("#selectall").click(function() {
if (!$(this).is(':checked'))
{
$('.allcheck').each(function(){
$(this).prop("checked", false);
});
}
else
{
$('.allcheck').each(function(){
$(this).prop("checked", true);
});
}
});
When user unchecks the box all should be unchecked , I guess that is also an expected functionality
NOTE : - I have given this answer assuming that you are using jquery
Try this:
function checkAll(id) {
var checkboxCollection = document.getElementById('<%= chkint.ClientID %>').getElementsByTagName('input');
for (var i = 0; i < checkboxCollection.length; i++) {
if (checkboxCollection[i].type.toString().toLowerCase() == "checkbox") {
checkboxCollection[i].checked = id.checked;
}
}
}
function select() {
var count = 0;
var chkSelectAll = document.getElementById('<%= selectall.ClientID %>');
var chkList = document.getElementById('<%= chkint.ClientID %>').getElementsByTagName("input");
for (var i = 0; i < chkList.length; i++) {
if (chkList[i].checked == true) {
count++;
}
}
if (count == chkList.length)
chkSelectAll.checked = true;
else
chkSelectAll.checked = false;
}
In this code, chkint is the ID of Checkboxlist and selectall is the ID of selectall checkbox.
Similar to Aravind, using jQuery you could group all your checkboxes in a container and give it an ID and give your SelectAll checkbox an ID. After that code is simple, see alse here for fiddle:
$("#selectall").click(function() {
if ($(this).is(':checked'))
$("#selectallcontainer :checkbox").not(this).attr('checked', true);
else
$("#selectallcontainer :checkbox").not(this).attr('checked', false);
});​
Here is a pure javascript solution:
jsFiddle here.
Simply attach the function to the onClick event of your 'Select All' checkbox and wrap the rest of your options in a div like so:
<script>
function checkAll() {
var checkbox_options = document.getElementById("checkbox_options");
var checkbox_all = document.getElementById("checkbox_all");
var checkboxes = checkbox_options.getElementsByTagName("input");
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = checkbox_all.checked;
}
}
</script>
<label><input id="checkbox_all" type="checkbox" onclick="checkAll()" />Select All</label><br />
<div id="checkbox_options">
<label><input type="checkbox" />CheckBox1</label><br />
<label><input type="checkbox" />CheckBox2</label><br />
<label><input type="checkbox" />CheckBox3</label><br />
</div>

Categories

Resources