Jquery change checkbox when clicking other checkbox - javascript

I have a list of checkboxes like this:
<input type='checkbox' name='cat' class='parent' value='cat1' />Category 1</input>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 1</input>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 2</input>
<input type='checkbox' name='cat' class='parent' value='cat2' />Category 2</input>
<input type='checkbox' name='foo' class='child' value='3' />SubCategory 3</input>
<input type='checkbox' name='foo' class='child' value='4' />SubCategory 4</input>
I would like to change the 'Category 1' checkbox to checked whenever I click it's subcategories without checking the other categories checkbox.
How can I do that?

Using the data attribute to set the cat. simply get this form the check event of the child elements:
<input type='checkbox' name='cat' class='parent' value='cat1' id="category1" />Category 1</input>
<input type='checkbox' name='foo' class='child' value='1' data-cat="1" />SubCategory 1</input>
<input type='checkbox' name='foo' class='child' value='2' data-cat="1" />SubCategory 2</input>
....
$('.child').change(function() {
var cat = $(this).data('cat');
$('#category' + cat).prop('checked', true);
});

I made a slight change to your markup and wrapped the sets in a div each.
Now my code will uncheck the parent too if all its child-cats are unchecked and when you check the parent, all child cats are checked/unchecked
Live Demo
$(function() {
$(".child").on("click",function() {
$parent = $(this).prevAll(".parent");
if ($(this).is(":checked")) $parent.prop("checked",true);
else {
var len = $(this).parent().find(".child:checked").length;
$parent.prop("checked",len>0);
}
});
$(".parent").on("click",function() {
$(this).parent().find(".child").prop("checked",this.checked);
});
});

You can id the subCategories as cat2_1, cat2_2 etc and then access the category element by means of the subcategory element by splitting the id by _ to obtain the category id.

Other answer
$(document).ready(function () {
$("INPUT").click(function () {
if ($(this).attr("class") == "parent") {
var v = this.value;
var check = this.checked;
var ok = false;
$("INPUT").each(function () {
if (v == this.value) {
ok = true;
} else {
if (this.name=="cat") ok = false;
else if (ok && this.name == "foo") {
this.checked=check;
}
}
});
}
});
});

Related

How can I select a random amount of checkboxes?

$('#select_all').on('click', function () {
if (this.checked) {
$('.check').each(function () {
this.checked = true;
});
} else {
$('.check').each(function () {
this.checked = false;
});
}
});
$('.check').on('click', function () {
if ($('.check:checked').length == $('.check').length) {
$('#select_all').prop('checked', true);
} else {
$('#select_all').prop('checked', false);
}
});
Need to alter this above Select All code to only select some random amount of check boxes, like below code example. Any help for this?
$(".random-pick").click(function() {
var maxAllowed = 6;
// Count checkboxes
var random_checkboxes = $("#content_subscribtion_ input.checkbox").size();
// Check random checkboxes until "maxAllowed" limit reached
while ($("#content_subscribtion_ input.checkbox:checked").size() < maxAllowed) {
// Pick random checkbox
var random_checkbox = Math.floor(Math.random() * random_checkboxes) + 1;
// Check it
$("#content_subscribtion_ input.checkbox:nth-child(" + random_checkbox + ")").prop("checked", true);
}
return false;
});
Using this tidy little shuffle method, we can create a random array of checkbox indexes, then slice it to a random number. We can then iterate and use jQuery's get() to find the checkbox index in the randomized array to check.
Array.prototype.shuffle = function() {
let m = this.length, i;
while (m) {
i = (Math.random() * m--) >>> 0;
[this[m], this[i]] = [this[i], this[m]]
}
return this;
}
$('#select_all').on('click', function() {
if ($(this).prop('checked')) {
let minnum = 3, maxnum = 6
let rand = Math.min(maxnum, Math.floor(Math.random() * ($('.check').length - 1 - minnum)) + minnum)
//create our keys array
let keyArray = [...Array($('.check').length).keys()].shuffle().slice(0, rand)
keyArray.forEach((chk_i, i) => {
if (i < rand) $($('.check').get(chk_i)).prop('checked', true)
})
} else {
$('.check').prop('checked', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Select all <input type='checkbox' id="select_all"></label>
<div class='cb'>
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
</div>
I have 8 checkboxes on the UI and I am selecting 3 checkboxes randomly. After each run, different checkboxes will be selected. Please use the exact/clean/proper checkbox common unique identifier in the cy.get('xxxxxx') and use following code in JS:
cy.get('section[class="table-body-cell checkbox-cell grid-1"] input')
.then(
($items) => {
return Cypress._.sampleSize($items.toArray(), 3)
})
.check({force: true});

Get Checkbox total count & save value in textbox if checked

I have written below code to get a total count of Checked chechbox and save the value checked value comma separated in textbox.
HTML:
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='1' onchange='checkCount(this.value);'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='2' onchange='checkCount(this.value);'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='3' onchange='checkCount(this.value);'></label>
<input type="text" name="proId" id="proId">
JS:
function checkCount(elm) {
var cheCount = $(":checkbox:checked").length;
document.getElementById('selectCount').innerHTML = cheCount;
definVal = document.getElementById('proId').value ;
var inval = elm+","+definVal;
document.getElementById('proId').value = inval;
if(cheCount==0){
document.getElementById('proId').value = "";
}
}
Check the output in below image:
My issue is that, when i unchecked the checkbox, its value is adding in textbox instead of getting remove.
Make below changes, just call js method dont send its value
And then check by their classname
function checkCount(elm) {
var checkboxes = document.getElementsByClassName("checkbox-btn");
var selected = [];
for (var i = 0; i < checkboxes.length; ++i) {
if(checkboxes[i].checked){
selected.push(checkboxes[i].value);
}
}
document.getElementById("proId").value = selected.join();
document.getElementById("total").innerHTML = selected.length;
}
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='1' onchange='checkCount();'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='2' onchange='checkCount();'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='3' onchange='checkCount();'></label>
<input type="text" name="proId" id="proId">
<div>Total Selected : <span id="total">0</span></div>

jquery: remove the selected value if checkbox is unchecked

I'm displaying list of items with checkbox, if checkbox is checked the value of selected item is displayed in different div.
Now, if I uncheck the checkbox I should remove the items displayed in the div.
Please help me how to fix this?
$('input[name="selectedItems1"]').click(function(){
if (this.checked) {
}else{
//what should go here
}
});
This example can help you:
html
<input type="checkbox" name="selectedItems1" value="val1" />
<input type="checkbox" name="selectedItems1" value="val2" />
<input type="checkbox" name="selectedItems1" value="val3" />
<div id="result"></div>
jquery
$('input[name="selectedItems1"]').click(function(){
if (this.checked) {
var span = "<span id='" + this.value + "'>" + this.value + "</span>";
$("#result").append(span);
}else{
$("#" + this.value).remove();//what should go here
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="selectedItems1" value="val1" />
<input type="checkbox" name="selectedItems1" value="val2" />
<input type="checkbox" name="selectedItems1" value="val3" />
<div id="result"></div>
Here is a way to accomplish your task. The following way also preserves the order in which the selected data is displayed.
var selectedItemsContainer = $('#selected');
var items = $('input[name="items"]');
items.on('change', function(){
selectedItemsContainer.empty();
var appendData = '';
$.each(items, function(i, item)
{
if ($(item).prop('checked'))
{
appendData +=$(item).val() + ' ';
}
});
selectedItemsContainer.append(appendData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="checkbox" name="items" value="Data 1">Data 1
<input type="checkbox" name="items" value="Data 2">Data 2
<input type="checkbox" name="items" value="Data 3">Data 3
<br>
<div id="selected"></div>

array of checkbox value checked and unchecked

I have this function, when I checked one or more checkbox the function load the value of the checked checkbox...but when I unchecked one or more check box the function show an empty array.
this is the function:
$(document).ready(function () {
$('input[type="checkbox"]').change(function () {
var mycheck = new Array();
if ($(this).is(':checked')) {
$("#line-checkbox-1:checked").each(function () {
mycheck.push($(this).val());//aggiungo value del checked
});
alert(mycheck)
} else {
var itemtoRemove = $(this);
mycheck.splice($.inArray(itemtoRemove, mycheck), 1); //rimuovo il value del dechecked
alert(mycheck);
}
});
This is HTML of the checkbox:
<div class="col-lg-3">
<input tabindex="17" id="line-checkbox-1" type="checkbox" name="servizi" value="3">
</div>
Try This Simple Script, this works for you:
HTML
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
JQUERY
$(document).ready(function ()
{
$('input[type="checkbox"]').change(function ()
{
var arr = $.map($('input:checkbox:checked'), function(e,i) {
return +e.value;
});
alert(arr);
});
});
Its probably because you are using id to reference the checkboxes and since you are creating the array from scratch everytime user changes a checkbox. you should recheck the list everytime a checkbox is changed. That means you dont need that if.( if($(this).is(":checked") )
$('.checkboxes input[type="checkbox"]').change(function () {
var mycheck = new Array();
$(".checkboxes input[type='checkbox']:checked").each(function () {
if ($(this).is(':checked')) {
mycheck.push($(this).attr("id") + ": is " + $(this).val()); //aggiungo value del checked
}
});
alert(mycheck);
});
here is a fiddle if i understand correctly what you are trying to do

jQuery UI Sortable connectWith multiple lists: How to update form field with the number of list?

I have multiple lists working using sortable and connectWith, but I am having difficulty updating the hidden form field with the new list/column number after moving an item.
The code works fine for the updating the current position, but I can't get the Javascript working for the column number.
Here's the code I have so far:
<div id='column1' class='col'>
<div id='contentItem_1'>
ITEM 1
<input class='itemcurrposition' type='hidden' name='item[1][currposition]' value='1' />
<input class='itemcolumnnum' type='hidden' name='item[1][columnnum]' value='1' />
</div>
<div id='contentItem_2'>
ITEM 2
<input class='itemcurrposition' type='hidden' name='item[2][currposition]' value='2' />
<input class='itemcolumnnum' type='hidden' name='item[2][columnnum]' value='1' />
</div>
</div>
<div id='column2' class='col'>
<div id='contentItem_3'>
ITEM 3
<input class='itemcurrposition' type='hidden' name='item[3][currposition]' value='3' />
<input class='itemcolumnnum' type='hidden' name='item[3][columnnum]' value='2' />
</div>
<div id='contentItem_4'>
ITEM 4
<input class='itemcurrposition' type='hidden' name='item[4][currposition]' value='4' />
<input class='itemcolumnnum' type='hidden' name='item[4][columnnum]' value='2' />
</div>
</div>
<div id='column3' class='col'>
<div id='contentItem_5'>
ITEM 5
<input class='itemcurrposition' type='hidden' name='item[5][currposition]' value='5' />
<input class='itemcolumnnum' type='hidden' name='item[5][columnnum]' value='3' />
</div>
<div id='contentItem_6'>
ITEM 6
<input class='itemcurrposition' type='hidden' name='item[6][currposition]' value='6' />
<input class='itemcolumnnum' type='hidden' name='item[6][columnnum]' value='3' />
</div>
</div>
$(document).ready (function () {
$('#column1, #column2, #column3').sortable ({
connectWith: '.col',
stop: function () {
var inputs2 = $('input.itemcurrposition');
var nbElems2 = inputs2.length;
$('input.itemcurrposition').each(function(idx) {
$(this).val(nbElems2 - idx);
});
}
})
});
Thanks for the help.
You can add event and ui arguments in your "stop" event handler, use ui.item to retrieve dragged item, then set value of its input to the index of parent column.
stop: function (event, ui) {
var inputs2 = $('input.itemcurrposition');
var nbElems2 = inputs2.length;
$('input.itemcurrposition').each(function(idx) {
$(this).val(nbElems2 - idx);
});
var newval = ui.item.closest('.col').index()+1;
ui.item.find("input.itemcolumnnum").val(newval);
}
if the column number depends on column id and not its index you can get it like this:
var newval = ui.item.closest('.col').attr('id').replace("column", "");
here jsfiddle with updated code

Categories