Unchecking checkbox value using javascript and jquery - javascript

I am generating 5 checkboxes dynamically. I can select upto 3 checkboxes. Once 3 checkboxes are selected, If I try to select one more checkbox it should give an alert and once i click ok on the alert box the fourth checkbox that I have selected should be unchecked.
Code I am using for generating checkboxes dynamically
$("#catalog_table").append('<tr><td style="width:10%; background-color:#fcfbf6; font-family:Proxima Nova Regular; font-size:11pt; font-color:#443b33;text-align: center;">'+productCatalog[i].productCode+'</td><td style="width:10%; background-color:#fcfbf6; text-align: center;font-family:Proxima Nova Regular; font-size:11pt; font-color:#443b33;">'+productCatalog[i].productName
+'</td><td style="width:10%; background-color:#fcfbf6; font-family:Proxima Nova Regular; font-size:11pt; font-color:#443b33; text-align: center;"><input type="checkbox" style="background-color:#fcfbf6;" name="chkOccupancy" class="chkbox" value='+productCatalog[i].productCode+'></td></tr>');
I tried number of ways...but all are getting unchecked.Can anyone tell me how to do this.

This should work for you
$(document).ready(function () {
$(':checkbox').click(function() {
if($(':checkbox:checked').length > 3){
alert('you can not check more than 3 checkboxes');
$(this).prop('checked',false);
}
});
})

Try this example:
$(function () {
$(document).on('change', 'input[name=chkOccupancy]', function (e) {
var chk = $(this);
var cnt = $('input[name=chkOccupancy]:checked').length;
if(3 < cnt) {
chk.prop('checked', false);
alert('Not more than 3 !');
}
e.stopPropagation();
});
});

As an alternative, here's a non–jQuery option. You can put a single listener on an an ancestor element, say a div, and prevent a fourth checkbox from being checked:
function checkCBs(e) {
var el = e.target;
if (el.type == 'checkbox' && document.querySelectorAll('input:checked').length > 3) {
el.checked = false;
}
}
You might want to qualify the selector to keep it within the div or for inputs with a particular class. Sample markup:
<div onclick="checkCBs(event)">
<label for="cb0">stuff<input type="checkbox" name="cb0" id="cb0">0</label><br>
<label for="cb1">stuff<input type="checkbox" name="cb1" id="cb1">1</label><br>
<label for="cb2">stuff<input type="checkbox" name="cb2" id="cb2">2</label><br>
<label for="cb3">stuff<input type="checkbox" name="cb3" id="cb3">3</label><br>
<label for="cb4">stuff<input type="checkbox" name="cb4" id="cb4">4</label><br>
</div>

Related

Can't Limit Number of Checked Checkboxes

Not sure why the script doesn't work. Want it to uncheck one box when you try to select more than two. For example if you select CHEAP and FAST and then try and select GOOD, FAST is then unchecked.
document.querySelector('body').className = 'has-js';
var checked = [];
[].forEach.call(document.querySelectorAll('input[type="checkbox"]'), function (checkbox) {
checkbox.addEventListener('change', function (e) {
ga('send', 'event', 'checkbox', 'trigger');
if (checkbox.checked && checked.length === 2) {
var uncheckTarget = checked[Math.floor(Math.random() * checked.length)];
uncheckTarget.checked = false;
}
checked = document.querySelectorAll('input[type="checkbox"]:checked');
});
});
<div class="container">
<input type="checkbox" id="fast">
<label class="red" for="fast">FAST</label>
<input type="checkbox" id="good">
<label class="green" for="good">GOOD</label>
<input type="checkbox" id="cheap">
<label class="blue" for="cheap">CHEAP</label>
</div>
Your solution seems to be overly complicated. Also, you should use the click event instead of the change event for your callback because by the time change occurs, the checkmark is already present in the checkbox, so now you'd have to remove it. With click, you can just cancel the event, which occurs prior to the checkmark going into the checkbox.
var boxes = Array.prototype.slice.call(document.querySelectorAll('input[type="checkbox"]'));
boxes.forEach(function(chk) {
chk.addEventListener('click', function (e) {
if (document.querySelectorAll("input[type=checkbox]:checked").length > 2) {
e.preventDefault();
alert("You already have 2 checkboxes checked. Uncheck one and try again!");
}
});
});
<div class="container">
<input type="checkbox" id="fast"><label class="red" for="fast">FAST</label>
<input type="checkbox" id="good"><label class="green" for="good">GOOD</label>
<input type="checkbox" id="cheap"><label class="blue" for="cheap">CHEAP</label>
</div>

Hiding and showing html elements with radio button and javascript style=none

I am trying to write a function that will show or hide an html element (contained in a div) using javascript. Right now I have 3 radio buttons (to eventually show/hide 3 elements depending on radio button selected, but right now I am just trying to hide one element (month) if year or week is selected, and to show it if month is selected. My html is:
<div id="setting">
<input type="radio" id="year" name="view" value="year"> year<br>
<input type="radio" id="month" name="view" value="month"> month<br>
<input type="radio" id="week" name="view" value="week"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
My javascript is:
function defineSetting (){
var setting = document.getElementById('setting').checked;
if(setting =='year'){
document.getElementById("cal").style.display = "none";
}else if(setting =='month'){
document.getElementById("cal").style.display = "unset";
}else if(setting =='week'){
document.getElementById("cal").style.display = "none";
}
}
I am also not super experienced with javascript and am trying to figure out how to call the function (if it works). If it is in the document ready function will it run when the page is loaded or do i need to call it somewhere.
I think this is what you're going for. You want to add an event listener to the buttons, and pass the value of the input that's checked to the defineSetting() function that hides/shows your #cal element. I also simplified your test in defineSetting()
<div id="setting">
<input type="radio" id="year" name="view" value="year" class="setting"> year<br>
<input type="radio" id="month" name="view" value="month" class="setting"> month<br>
<input type="radio" id="week" name="view" value="week" class="setting"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
<style>
.hidden { display: none; }
</style>
<script>
var inputs = document.getElementsByClassName('setting'),
setting;
for (var i = 0; i < inputs.length; i++) {
var el = inputs[i];
el.addEventListener('change', function() {
defineSetting(this.value);
})
}
function defineSetting(setting) {
if (setting == 'year' || setting == 'week') {
document.getElementById("cal").classList.add('hidden');
} else {
document.getElementById("cal").classList.remove('hidden');
}
}
</script>
This will help you out:
How to get value of selected radio button?
You are trying to get the checked value of a div element, but this element doesn't have that. The input element do have that property so that's where you can get it from.

Div sorting through multiple checkbox selection

In my page there are several Div that hold rating point and also some checkbox. Basically i want based on checkbox selection Div rating will show.i don't know how do that through jquery.
for Example
<div id="ratingbox">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>
<div id="chkbox">
<input type="checkbox" class="ratingCheckbox" value="1" onclick="selection()">1
<input type="checkbox" class="ratingCheckbox" value="2" onclick="selection()">2
<input type="checkbox" class="ratingCheckbox" value="3" onclick="selection()">3
<input type="checkbox" class="ratingCheckbox" value="4" onclick="selection()">4
<input type="checkbox" class="ratingCheckbox" value="5" onclick="selection()">5</div>
LINK
if checkbox 1 is checked, span with value 1 will be visible and all others will be hidden, If checkbox 1 and 4 are checked span with value 1 and span with value 4 are only visible and rest are hidden. if no checkbox is checked then all are visible.
You can do something like this
$('.ratingCheckbox').on('click', function(){
$('span:contains('+this.value+')').toggle();
});
And hide the spans by default with this in css display: none;
Check the demo here http://jsfiddle.net/dhirajbodicherla/dnyfmhyx/4/
Update
Try something like this
var checkbox = $('.ratingCheckbox').on('change', function () {
var val = checkbox.map(function (index, el) {
return (el.checked) ? +$(el).val() : undefined;
}).get(); // this will get the list of checked values in an array like this - [1,4]
if (val.length > 0) { // if at least one checkbox is checked
$('span').hide(); // hide all
$('span').filter(function (index, el) { // this will get all the spans which have value 1 and 4 from the above array
return $.inArray(+$(el).text(), val) != -1 ? el : undefined;
}).show(); // show the ones that are checked
} else {
$('span').show(); // if no checkbox is checked show everything
}
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/dnyfmhyx/5/
I give the spans display: none; when the corresponding checkbox is check I add .visible class to them:
#ratingbox > span {
/* other styles */
display: none;
}
#ratingbox > span.visible {
display:inline-block;
}
In the jQuery part we just need to get the value of the new changed checkbox and toggle the visible class of corresponding spans (I used onchange instead of onclick):
$('#chkbox > input[type=checkbox]').on('change', function() {
var val = $(this).val();
$('#ratingbox > span').each(function() {
if($(this).text() == val)
$(this).toggleClass('visible');
});
});
jsfiddle DEMO

CheckAll/UncheckAll checkbox with jQuery

I have made a check-box checkall/uncheckall.
HTML
<div> Using Check all function </div>
<div id="selectCheckBox">
<input type="checkbox" class="all" onchange="checkAll('selectCheckBox','all','check','true');" />Select All
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 1
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 2
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 3
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 4
</div>
main.js
function checkAll(parentId,allClass,checkboxClass,allChecked){
checkboxAll = $('#'+parentId+' .'+allClass);
otherCheckBox = $('#'+parentId+' .'+checkboxClass);
checkedCheckBox = otherCheckBox.filter($('input[type=checkbox]:checked'));
if(allChecked=='false'){
if(otherCheckBox.size()==checkedCheckBox.size()){
checkboxAll.attr('checked',true);
}else{
checkboxAll.attr('checked',false);
}
}else{
if(checkboxAll.attr('checked')){
otherCheckBox.attr('checked',true);
}else{
otherCheckBox.attr('checked',false);
}
}
}
It works fine. But get bulky when I have whole lot of checkboxes. I want to do same work by using jQuery rather than putting onchange on each checkbox. I tried different sort of things but couldnot work. I tried following one:
$('.check input[type="checkbox"]').change(function(e){
checkAll('selectCheckBox','all','check','true');
});
to do same work as onchange event but didnot work. Where do I went wrong.
I think you just need this: You do not need to pass all the arguments and have the inline onchange event attached to it. You can simplify your code.
$(function () {
$('input[type="checkbox"]').change(function (e) {
if(this.className == 'all')
{
$('.check').prop('checked', this.checked); //Toggle all checkboxes based on `.all` check box check status
}
else
{
$('.all').prop('checked', $('.check:checked').length == $('.check').length); // toggle all check box based on whether all others are checked or not.
}
});
});
Demo
Your selector is wrong:
.check input[type="checkbox"]
Above selects any input of type checkbox that has the ancestor with class .check. It'll match this:
<div class="check">
<input type="checkbox".../>
</div>
it should be:
input.check[type="checkbox"]
You closed the string here $('.check input[type='checkbox']') instead, you should use double quotes $('.check input[type="checkbox"]')

hiding div based on unchecking checkboxes

I have multiple checkboxes in a form. Based on clicking those checkboxes, I show a div section. But if I uncheck even one checkbox, that div section gets hidden. How do I make sure that div section is hidden only if all checkboxes are unchecked. Crude way can be to write my own 'display' method which will check if all checkboxes are unchecked and then hide the div section. Any easier solution??
HTML:
<input type="checkbox" class="group" name="check1">
<input type="checkbox" class="group" name="check2">
<input type="checkbox" class="group" name="check3">
<input type="checkbox" class="group" name="check4">
jQuery:
$(function() {
var $checks = $('input:checkbox.group');
$checks.click(function() {
if($checks.filter(':checked').length == 0) {
$('#div').hide();
} else {
$('#div').show();
}
});
});
The following code will show the div if one or more checkboxes has been checked:
jQuery
Version 1:
$("input[name='mycheckboxes']").change(function() {
$("#showme").toggle($("input[name='mycheckboxes']:checked").length>0);
});
Version 2 (more efficient):
var MyCheckboxes=$("input[name='mycheckboxes']");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<div id="showme" style="display: none">Show me</div>
Code in action (Version 1).
Code in action (Version 2).
--- Different Checkbox Names Version ---
For different named checkboxes, wrap them in a DIV with an identifier. E.g.
jQuery
var MyCheckboxes=$("#checkboxgroup :checkbox");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<div id="checkboxgroup">
<input type="checkbox" name="mycheckbox1" />
<input type="checkbox" name="mycheckbox2" />
<input type="checkbox" name="mycheckbox3" />
<input type="checkbox" name="mycheckbox4" />
</div>
<div id="showme" style="display: none">Show me</div>
This code in action.
Not really, you need Javascript for this one... Or maybe... Let's say:
<html>
<head>
<style type="text/css">
#input_container > input + input + input + div {display:none}
#input_container > input:checked + input:checked + input:checked + div {display:block}
</style>
</head>
<div id="input_container">
<input type="checkbox">blah1
<input type="checkbox">blah2
<input type="checkbox">blah3
<div>To show/hide</div>
</div>
</body>
</html>
I'd create a function that uses a variable that tracks the number of checkboxes checked:
var numberOfChecks = 0;
function display(ev) {
var e = ev||window.event;
if (this.checked) {
numberOfChecks++;
} else {
numberOfChecks--;
}
if (!numberOfChecks) {
//hide div code
} else {
//display div code
}
}
Use that function for each onClick event for every checkbox. In the ideal world this would be done inside some initialization function so that numberOfChecks and display aren't in the global namespace.
Plain Javascript:
HTML
<div id="checkboxes">
<input type="checkbox" name="check1">
<input type="checkbox" name="check2">
<input type="checkbox" name="check3">
<input type="checkbox" name="check4">
</div>
<div id="hiddendiv"><!-- more stuff --></div>
Javascript
(function() { //Create clousre to hide the checked variable
var checked = 0;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
for (var i=0, l=inputs.length; i<l; i++) {
if (inputs[i].type == 'checkbox') {
if (inputs[i].checked) checked++; //Count checkboxes that might be checked on page load
inputs[i].onchange = function() {
checked += this.checked ? 1 : -1;
var hiddendiv = document.getElementById('hiddendiv');
if (!checked) hiddendiv.style.display = "none";
else hiddendiv.style.display = "";
};
}
}
}());
The other option is to simply iterate through each checkbox every time the change event is fired rather than relying on counting, which is probably more error prone. Obviously jQuery is more concise, but a little verbosity never hurt anyone.
function toggleCheckbox(id) {
if ($("input[id=" + id + "]").is(':checked')) {
$( "#"+id ).prop( "checked", false );
} else {
$( "#"+id ).prop( "checked", true );
}
}
Just pass the id of your checkbox

Categories