This function alerts right totalqt only when I check checkboxes one by one. But doesn't work properly for #check_all: alerts totalqt = 0.
What I did wrong, can anyone explain?
var totalqt=0;
$('#check_all').click( function() {
$('.checkbox').click();
alert(totalqt);
} );
$('.checkbox').click(function(e) {
e.stopPropagation();
if($(this).closest("tr").not('#hdr').hasClass("row_selected")){
$(this).closest("tr").not('#hdr').removeClass("row_selected");
totalqt=totalqt - parseInt($(this).closest("tr").find("#qt").text(), 10);
}
else {
$(this).closest("tr").not('#hdr').addClass("row_selected");
totalqt=totalqt + parseInt($(this).closest("tr").find("#qt").text());
}
HTML looks like that
<tr>
...
<td><input type="checkbox" name="checkbox[]" method="post" value="" class="checkbox"/></td>
...
</tr>
actually when the checkbox is changed manualy it doesn't trigger handler. try something like this.
function doIt(obj){
if($(obj).closest("tr").not('#hdr').hasClass("row_selected")){
$(obj).closest("tr").not('#hdr').removeClass("row_selected");
totalqt=totalqt - parseInt($(obj).closest("tr").find("#qt").text(), 10);
}
else {
$(obj).closest("tr").not('#hdr').addClass("row_selected");
totalqt=totalqt + parseInt($(obj).closest("tr").find("#qt").text());
}
}
then
$('.checkbox').click(function(e) {
e.stopPropagation();
doIt(this);
});
and
$('#check_all').click( function() {
if($(this).prop('checked')){
$('.checkbox').each(function(){
$(this).prop('checked', true);
doIt(this);
alert(totalqt);
});
}else{
$('.checkbox').each(function(){
$(this).prop('checked', false);
doIt(this);
alert(totalqt);
});
}
} );
I have changed my answer to the following, try this:
<div class="checkall">
<input type="checkbox" id="checkall">
</div>
<div id="list">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
and jquery:
var checkboxes = $(":checkbox", "#list").change(function() {
var allIsChecked = checkboxes.length === checkboxes.filter(":checked").length;
checkAll[0].checked = allIsChecked;
});
var checkAll = $("#checkall").change(function() {
checkboxes.prop("checked",this.checked);
});
Related
I have a checkboxs 3-4 of them, when the user checks the checkbox I want to add the value of the checkbox to the array, if they uncheck the box I want to remove the item from the array, this is what I got so far:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
if ($(this).attr("id") == 'price') {
if (this.checked) {
priceArray.push($(this).val());
}
else {
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
}
}
});
});
Adding the value to the array works perfectly, however removing items results in this error:
Cannot read property 'toLowerCase' of undefined
on this line:
return value != $(this).val();
Run the code snippet and check
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var priceArray=[];
$(document).ready(function(){
$('input[type=checkbox]').each(function () {
$(this).change(function () {
if (this.checked) {
priceArray.push($(this).val());
$("#displayarray").html("array=[" + priceArray+"]");
}
else {
var index = priceArray.indexOf($(this).val());
if (index > -1) {
priceArray.splice(index, 1);
}
$("#displayarray").html("array=[" + priceArray+"]");
}
});
});
});
</script>
<input type="checkbox" value="box1"/>box1
<input type="checkbox" value="box2"/>box2
<input type="checkbox" value="box3"/>box3
<input type="checkbox" value="box4"/>box4
<br/>
<div id="displayarray"></div>
Replace
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
By
val = $(this).val();
priceArray = jQuery.grep(priceArray, function (value) {
return value != val;
});
Don't forget the scope where your are in the callback function.
You can try using filter instead of $.grep:
var values = [];
$("input").on("change", function()
{
var $this = $(this);
if ($this.is(":checked"))
{
values.push($this.val());
}
else
{
values = values.filter(x => x != $this.val());
}
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />
filter() is a native function, I prefer using built-in function rather than 3rd party's, IMO. Also, avoid binding events within loops like this:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
Use this method:
$('ul.dropdown-menu').on('change', 'input[type=checkbox]', function() { ...
This will work even if checkbox is dynamically added.
You could do this very cleanly with a functional style
<div class="checkboxes">
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
</div>
And
(function() {
$(".checkboxes input[type=checkbox]").on("click", function() {
var x = $(".checkboxes input[type=checkbox]:checked").map(function(a,b) {
return parseFloat(b.value);
}).toArray();
console.log(x)
});
})();
I had a similar situation and I was able to overcome it in the following way :
My jQuery :
$(document).ready(function(){
$("#dataFilterForm").on("input", function() {
var values = '';
var boxes = $('input[name=vehicle]:checked');
boxes.each(function(b){
values = values + boxes[b].id + ', ';
});
$('#filterResult').text(values.substring(0, values.length-2));
});
});
My HTML :
<form id="dataFilterForm">
<input type="checkbox" id="Filter1" name="vehicle" value="Bike">
<label for="Filter1">Filter1</label><br>
<input type="checkbox" id="Filter2" name="vehicle" value="Car">
<label for="Filter2">Filter2</label><br>
<input type="checkbox" id="Filter3" name="vehicle" value="Boat">
<label for="Filter3">Filter3</label><br>
</form>
<p>Result : </p>
<p id="filterResult"></p>
I have the following HTML:
<div class="pricing-levels-3">
<p><strong>Which level would you like? (Select 3 Levels)</strong></p>
<input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
</div>
Live site:
http://www.chineselearnonline.com/amember/signup20.php
How can I do it so that the user can only select 3 of those checkboxes?
Using change event you can do something like this:
var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
}
});
See this working demo
Try like this.
On change event,
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
alert("allowed only 3");
}
});
Check this in JSFiddle
Try this DEMO:
$(document).ready(function () {
$("input[name='vehicle']").change(function () {
var maxAllowed = 3;
var cnt = $("input[name='vehicle']:checked").length;
if (cnt > maxAllowed)
{
$(this).prop("checked", "");
alert('Select maximum ' + maxAllowed + ' Levels!');
}
});
});
$('.checkbox').click(function(){
if ($('.checkbox:checked').length >= 3) {
$(".checkbox").not(":checked").attr("disabled",true);
}
else
$(".checkbox").not(":checked").removeAttr('disabled');
});
i used this.
I think we should use click instead change
Working DEMO
$("input:checkbox").click(function(){
if ($("input:checkbox:checked").length > 3){
return false;
}
});
Working DEMO
Try this
var theCheckboxes = $(".pricing-levels-3 input[type='checkbox']");
theCheckboxes.click(function()
{
if (theCheckboxes.filter(":checked").length > 3)
$(this).removeAttr("checked");
});
I'd say like letiagoalves said, but you might have more than one checkbox question in your form, so I'd recommend to do like this:
var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($('input.single-checkbox').siblings('input.single-checkbox:checked').length > limit) {
this.checked = false;
}
});
(function ($) {
$(document).ready(function () {
$(document).on("change", ".pricing-levels-3 input", function () {
var numberOfChecked = $(".pricing-levels-3 input:checkbox:checked").length;
if (numberOfChecked >= 2) {
$(".pricing-levels-3 input:not(:checked)").prop("disabled", true);
} else {
$(".pricing-levels-3 input:not(:checked)").removeAttr("disabled", true);
}
});
});
})(jQuery);
This is working for me with checkbox name.
<script>
// limit checkbox select
$('input[name=vehicle]').on('change', function (e) {
if ($('input[name=vehicle]:checked').length > 3) {
$(this).prop('checked', false);
alert("allowed only 3");
}
});
</script>
This is how I made it work:
// Function to check and disable checkbox
function limit_checked( element, size ) {
var bol = $( element + ':checked').length >= size;
$(element).not(':checked').attr('disabled',bol);
}
// List of checkbox groups to check
var check_elements = [
{ id: '.group1 input[type=checkbox]', size: 2 },
{ id: '.group2 input[type=checkbox]', size: 3 },
];
// Run function for each group in list
$(check_elements).each( function(index, element) {
// Limit checked on window load
$(window).load( function() {
limit_checked( element.id, element.size );
})
// Limit checked on click
$(element.id).click(function() {
limit_checked( element.id, element.size );
});
});
I have Alter this function to auto uncheck previous
var limit = 3;
$('.compare_items').on('click', function(evt) {
index = $(this).parent('td').parent('tr').index();
if ($('.compare_items:checked').length >= limit) {
$('.compare_items').eq(localStorage.getItem('last-checked-item')).removeAttr('checked');
//this.checked = false;
}
localStorage.setItem('last-checked-item', index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="compare_items">1
<input type="checkbox" class="compare_items">2
<input type="checkbox" class="compare_items">3
<input type="checkbox" class="compare_items">4
<input type="checkbox" class="compare_items">5
<input type="checkbox" class="compare_items">6
<input type="checkbox" class="compare_items">7
<input type="checkbox" class="compare_items">8
<input type="checkbox" class="compare_items">9
<input type="checkbox" class="compare_items">10
I did this today, the difference being I wanted to uncheck the oldest checkbox instead of stopping the user from checking a new one:
let maxCheckedArray = [];
let assessmentOptions = jQuery('.checkbox-fields').find('input[type="checkbox"]');
assessmentOptions.on('change', function() {
let checked = jQuery(this).prop('checked');
if(checked) {
maxCheckedArray.push(jQuery(this));
}
if(maxCheckedArray.length >= 3) {
let old_item = maxCheckedArray.shift();
old_item.prop('checked', false);
}
});
This method works well with checkboxes in a container, such as bootstrap checkbox
const checkedLimmit = 2;
function ValidateCheckBoxGroup(container) {
if (container.find('input[type="checkbox"]:checked').length >= checkedLimmit) {
container.find('input[type="checkbox"]:not(:checked)').prop('disabled', true);
container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').addClass('disabled');
} else {
container.find('input[type="checkbox"]:not(:checked)').prop('disabled', false);
container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').removeClass('disabled');
}
}
$(function () {
// validate containers on page load
$('div.checkbox-group').each(function () {
ValidateCheckBoxGroup($(this));
});
// set checkbox events
$('div.checkbox-group input[type="checkbox"]').change(function () {
ValidateCheckBoxGroup($(this).closest("div.checkbox-group"));
});
});
JS and HTML
This worked for me what it does is that, the onclick function checkControl() will count the number of times the checkbox has been clicked then if it's greater than 3 display error message.
function checkboxControl(j) {
var total = 0;
var elem = document.getElementsByClassName("checkbox");
var error = document.getElementById("error");
for (var i = 0; i < elem.length; i++) {
if (elem[i].checked == true) {
total = total + 1;
}
if (total > 3) {
error.textContent = "You Must Select at Least 3";
elem[j].checked = false;
return false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="">
<span id="error" style="color: red"></span>
<br>
<span>Python</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(0)"
id="1"
/>
<br>
<span>Javascript</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(1)"
id="1"
/><br>
<span>Go</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(2)"
id="1"
/><br>
<span>Laravel</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(3)"
id="1"
/>
</form>
</body>
</html>
This resources helped me understand
https://www.plus2net.com/javascript_tutorial/checkbox-limit-demo2.php
If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox
var queue = [];
function checking(id){
queue.push(id)
if (queue.length===3){
queue[0].checked = false
queue.shift()
}
}
This function simply checks if you have just checked a checkbox. If yes, it increments the checked value by one. If it reaches the limit then the next checkbox is rejected.
var limit = 3;
var checked = 0;
$('.single-checkbox').on('change', function() {
if($(this).is(':checked'))
checked = checked+1;
if($(this).is(':checked') == false)
checked = checked-1;
if(checked > limit) {
this.checked = false;
checked = limit;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pricing-levels-3">
<p><strong>Which level would you like? (Select 3 Levels)</strong></p>
<input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
</div>
I have some checkboxes which feature days of the week. I simply want to loop through, and display all those selected within an append.
HTML
<div class="col-lg-8">
<input type="checkbox" value="Mon" class="dayname" name="days[]"> M
<input type="checkbox" value="Tues" class="dayname" name="days[]"> T
<input type="checkbox" value="Wed" class="dayname" name="days[]">W
<input type="checkbox" value="Thurs" class="dayname" name="days[]">T
<input type="checkbox" value="Fri" class="dayname" name="days[]">F
<input type="checkbox" value="Sat" class="dayname" name="days[]">S
<input type="checkbox" value="Sun" class="dayname" name="days[]">S
</div>
Javascript
$(".dayname").click(function() {
alert( $(this).attr("name") );
$('.dayname').val();
});
Try this: JSFIDDLE
$(".dayname").click(function() {
alert( $(this).attr("name") );
$('#log').html(''); // Clears the log div
$('.dayname:checked').each(function(e){
$('#log').append('<p>'+$(this).val()+'</p>');
});
});
Use .map().get():
$(".dayname").change(function() {
var days = $('.dayname:checked').map(function(){
return this.value;
}).get();
console.log(days); // prints the checked checkboxes values
});
var checkedDays=[];
$(".dayname").click(function() {
//alert( $(this).attr("name") );
$('.dayname:checked').each(function(e){
//alert($(this).val());
});
checkedDays.push($(this).val());
alert(checkedDays);
});
$(".dayname").click(function() {
alert( $(this).attr("value") );
});
Or
$(".dayname").change(function() {
if($(this).is(":checked")) {
alert($(this).attr('value'));
}
});
I have a links named All and none. When I click on All, I want it to check all checkboxes related with it and change it's link text to none.
When I click again I want it to uncheck all of the checkboxes.
I have some code which I can use to check all boxes with a checkbox. But now I want to check all boxes with a link. Please see, here is this demo code (also on jsfiddle):
<script type="text/javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
$(document).ready(function () {
$("input[type=checkbox]").click(updateCount);
updateCount();
function updateCount () {
var count = $("input[type=checkbox].case:checked").length;
$("#count").text(count);
$("#status").toggle(count > 0);
};
});
</script>enter code here
</head>
<body>
<H2>why counting wrong in crome, Ie </H2>
select all
<input type="checkbox" id="selectall"/>
<input type="checkbox" class="case" name="case" value="1"/>
<input type="checkbox" class="case" name="case" value="2"/>
<input type="checkbox" class="case" name="case" value="3"/>
<input type="checkbox" class="case" name="case" value="4"/>
<input type="checkbox" class="case" name="case" value="5"/>
<div id="status">
<p id="count">0</p>
</div>
</body>
http://jsfiddle.net/kdEmH/24/
Try to get it this way, i just guessed a link <a> with an id of #allNone and put the .prop() function to check and uncheck the checkboxes:
$('#allNone').on('click', function (e) {
e.preventDefault();
(this.text == 'Check All') ?
$(this).text('Check None').nextAll('.case').prop('checked', true) :
$(this).text('Check All').nextAll('.case').prop('checked', false);
});
Demo
In your HTML part, add a link like :
Click me to toggle all checkboxes
In your Javascript part, add :
$("a#select_all_link").click(function(){
if($('.case:checked').length > 0)
$('.case').attr('checked', false);
else
$('.case').attr('checked', true);
});
Please see working example here
Edit : Names now changed wrt checkboxes state (checked or not)
Try this: Demo :
Add a <A> tag to html code:
<a id="selectall" href="#">select all</a>
Add this function to java-script code:
$(function(){
var state=true;
$("#selectall").click(function () {
$('.case').attr('checked', state);
state=!state;
var obj = document.getElementById("selectall");
if(state)
{
obj.innerText="select all";
}
else
{
obj.innerText="clear all";
}
});
Complete Code
$(function(){
var state=true;
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', state);
state=!state;
var obj = document.getElementById("selectall");
if(state)
{
obj.innerText="select all";
}
else
{
obj.innerText="clear all";
}
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
$(document).ready(function () {
$("input[type=checkbox]").click(updateCount);
updateCount();
function updateCount () {
var count = $("input[type=checkbox].case:checked").length;
$("#count").text(count);
$("#status").toggle(count > 0);
};
});
Might not be what you're looking for, but it's a quick way of doing the toggle thing:
$('a').click(function() {
var $cbs = $('.case');
$cbs.prop('checked', !$cbs.prop('checked'));
return false;
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
All
<input type="checkbox" class="case" value="1"/>
<input type="checkbox" class="case" value="2"/>
<input type="checkbox" class="case" value="3"/>
<input type="checkbox" class="case" value="4"/>
<input type="checkbox" class="case" value="5"/>
<div id="status">
<p id="count">0</p>
</div>
</body>
<script type="text/javascript">
$("document").ready(function() {
$("#link").click(function(){
$a = $(this);
var action = $a.data('action');
if(action == "all"){
$('.case').attr("checked","true");
$a.text("None").data("action","none");
}
if(action == "none"){
$('.case').removeAttr("checked");
$a.text("All").data("action","all");
}
updatecount();
return false;
})
$(".case").click(function(){
if($(".case").length == $(".case:checked").length){
$("#link").text("None").data("action","none");
}else{
$("#link").text("All").data("action","all");
}
updatecount();
})
})
var updatecount = function(){
$("#count").text($(".case:checked").length);
}
</script>
</html>
Can anyone please tell me how to disable a textbox, if a checkbox is checked, and enable textbox if the checkbox is not checked?
Put this in the checkbox:
onclick="document.getElementById('IdOfTheTextbox').disabled=this.checked;"
<input type="text" id="textBox">
<input type="checkbox" id="checkBox" onclick="enableDisable(this.checked, 'textBox')">
<script language="javascript">
function enableDisable(bEnable, textBoxID)
{
document.getElementById(textBoxID).disabled = !bEnable
}
</script>
jQuery(document).ready(function () {
$("#checkBox").click(function () {
$('#textBox').attr("disabled", $(this).is(":checked"));
});
});
Create a Javascript function like this:
function EnableTextbox(ObjChkId,ObjTxtId)
{
if(document.getElementById(ObjChkId).checked)
document.getElementById(ObjTxtId).disabled = false;
else
document.getElementById(ObjTxtId).disabled = true;
}
Create a C# function like this on the grid RowDataBound:
protected void lstGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtAllowed = (TextBox)e.Row.FindControl("txtAllowed");
CheckBox chkAllowed = (CheckBox)e.Row.FindControl("RowSelector");
chkAllowed.Attributes.Add("onClick", "EnableTextbox('" + chkAllowed.ClientID + "', '" + txtAllowed.ClientID + "')");
}
}
I have the simplest solution yet for this Simple task.
Believe me or not it works
s = 1;
function check(){
o = document.getElementById('opt');
if(o.value=='Y'){
s++;
if(s%2==0)
$('#txt').prop('disabled',true);
else
$('#txt').prop('disabled',false);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text: <input type="text" name="txt" id="txt">
<input type="checkbox" name="opt" id="opt" value="Y" onclick="check()">
Here is code.
<script type="text/javascript">
function EnableDisableTextBox(chkPassport) {
var txtPassportNumber = document.getElementById("txtPassportNumber");
txtPassportNumber.disabled = chkPassport.checked ? false : true;
if (!txtPassportNumber.disabled) {
txtPassportNumber.focus();
}
}
</script>
<label for="chkPassport">
<input type="checkbox" id="chkPassport" onclick="EnableDisableTextBox(this)" />
Do you have Passport?
</label>
<br />
Passport Number:
<input type="text" id="txtPassportNumber" disabled="disabled" />
Using jQuery:
$("#checkbox").click(function(){
$("#textbox")[0].disabled = $(this).is(":checked");
});