I'm trying to reactivate a checkbox in a dynamic list and I do not succeed, the list update its contents every x time.
<div class="content">
<ul class="mylist">
<li><input type="checkbox" class="check" checked>0</li>
<li><input type="checkbox" class="check">1</li>
<li><input type="checkbox" class="check">2</li>
<li><input type="checkbox" class="check">3</li>
<li><input type="checkbox" class="check">4</li>
<li><input type="checkbox" class="check">5</li>
<li><input type="checkbox" class="check">6</li>
<li><input type="checkbox" class="check">7</li>
</ul>
</div>
// checkbox
var checkbox;
var list = [2,3,4,5,6,7,8,9];
//
setInterval(function(){
$('.mylist li').remove();
for(i in list) {
$('.mylist').append('<li><input type="checkbox" class="check">' + i + '</li>');
}
if(typeof checkbox === 'object')
checkbox.prop('checked', true);
}, 3000);
$('.check').on('click', function(){
if ($(this).is(":checked")) {
checkbox = $(this);
}
});
https://jsfiddle.net/ywkr5ezp/3/
The reason this is happening is because the input element stored in checkbox is not the same as the new input element that you are creating. When you store an element in a variable it is storing that specific instance of the element.
One way around this would be to give the checkbox elements id's that you could then reference and recheck.
Related
I'm wondering if there would be away to get the values of checked checkboxes and than use the values in the filter function in my DeleteObject function.
<div style="text-align:center" class="list">
<small>Walls:</small><input id="deleteCheckbox" type="checkbox" value="Wall">
<small>Doors:</small><input id="deleteCheckbox" type="checkbox" value="Door">
<small>Traps:</small><input id="deleteCheckbox" type="checkbox" value="SlowTrap"><br>
<small>Mines:</small><input id="deleteCheckbox" type="checkbox" value="GoldMine">
</div>
Javascript:
function DeleteObject() {
var b = Game.currentGame.ui.buildings;
Object.keys(b).filter(function(e) {
return CheckBoxValuesHere == b[e].type;
}).forEach(function(i) {
Game.currentGame.network.sendRpc({
name: "DeleteObject",
uid: b[i].uid
})
})
}
As mentioned in the comments, id's should be unique. To get the values of checked checkboxes, add change event to the input with type checkbox and then grab input with checked checkboxes.
document.querySelectorAll('input[type="checkbox"]')
.forEach(input => {
input.addEventListener('change', function() {
const values = [...document.querySelectorAll('input:checked')].map(input => input.value);
console.log(values);
});
});
<div style="text-align:center" class="list">
<small>Walls:</small><input id="deleteCheckbox" type="checkbox" value="Wall">
<small>Doors:</small><input id="deleteCheckbox" type="checkbox" value="Door">
<small>Traps:</small><input id="deleteCheckbox" type="checkbox" value="SlowTrap"><br>
<small>Mines:</small><input id="deleteCheckbox" type="checkbox" value="GoldMine">
</div>
function getItemsToDelete() {
// get a nodeList of all selected elements,
// convert it to an array and return an
// array of the values.
return Array.from(
document.querySelectorAll(
'input[name=deleteCheckbox]:checked'
)
).map( item => item.value );
}
console.log(getItemsToDelete());
<ul style="list-style:none">
<li><input name="deleteCheckbox" type="checkbox" value="Wall"><small>Walls</small></li>
<li><input name="deleteCheckbox" type="checkbox" value="Door" checked><small>Doors</small></li>
<li><input name="deleteCheckbox" type="checkbox" value="SlowTrap"><small>Traps</small></li>
<li><input name="deleteCheckbox" type="checkbox" value="GoldMine"><small>Mines</small></li>
</ul>
Add unique names or IDs to each checkbox and assign them listeners to click event (in JS code) or directly in HTML. Then in JS refer to checkbox value with document.getElementById(<ID>).value.
I want to make a separate function from my checkall and uncheckall button (I already have one working).
This time I want my checkall/uncheckall chekcbox checked if all children checkboxes are checked.
I was thinking maybe I can compare my checked children checkbox length from children checkbox length.
function testFunction() {
$('.cb').change(function(){
var checkedChildCheckBox = $('.cb:checked').length;
var numberOfChildCheckBoxes = $('.cb').length;
if (checkedChildCheckBox == numberOfChildCheckBoxes){
$("#checkAll").prop('checked', true);
}
})
}
Can someone give me some ideas on this? Still my checkall/uncheckall checkbox doesn't changed to checked. Conditions made was true in if statement.
Or maybe my idea of comparing length is not gonna work?
.cb my class for children checkbox
#checkall my id for parent or checkall/uncheckall checkbox
It is already working I guess - issue is putting the event listener inside a function (don't know why is that the case).
Anyway, see demo below:
var numberOfChildCheckBoxes = $('.cb').length;
$('.cb').change(function() {
var checkedChildCheckBox = $('.cb:checked').length;
if (checkedChildCheckBox == numberOfChildCheckBoxes)
$("#checkAll").prop('checked', true);
else
$("#checkAll").prop('checked', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="checkAll">All</label>
<input type="checkbox" id="checkAll" />
<br/>
<br/>
<input class="cb" type="checkbox" />
<input class="cb" type="checkbox" />
<input class="cb" type="checkbox" />
Try below code
Js
<script type="text/javascript">
$(document).ready(function(){
$('#select_all').on('click',function(){
if(this.checked){
$('.checkbox').each(function(){
this.checked = true;
});
}else{
$('.checkbox').each(function(){
this.checked = false;
});
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#select_all').prop('checked',true);
}else{
$('#select_all').prop('checked',false);
}
});
});
</script>
Html
<ul class="main">
<li><input type="checkbox" id="select_all" /> Select all</li>
<ul>
<li><input type="checkbox" class="checkbox" value="1"/>Item 1</li>
<li><input type="checkbox" class="checkbox" value="2"/>Item 2</li>
<li><input type="checkbox" class="checkbox" value="3"/>Item 3</li>
<li><input type="checkbox" class="checkbox" value="4"/>Item 4</li>
<li><input type="checkbox" class="checkbox" value="5"/>Item 5</li>
</ul>
</ul>
I have some checkboxes that I am getting the values into an array:
<ul>
<li><input type="checkbox" name="daily[]" value="0"></li>
<li><input type="checkbox" name="daily[]" value="1"></li>
<li><input type="checkbox" name="daily[]" value="2"></li>
<li><input type="checkbox" name="daily[]" value="3"></li>
<li><input type="checkbox" name="daily[]" value="4"></li>
</ul>
I am using this function to get the values into the array:
var days = $('input[name^='+daily+']:checked').map(function(){
return parseInt($(this).val(),10);
}).get();
This is working well..
But now I want to do the inverse.. To fill an edit form, I want to check the checkboxes when having the array. How could I do that in a good way?
Iterate the array - create a selector for the checkbox element - verify the element exists - set the checked property:
for (var i = 0; i < days.length; i++) {
var value = days[i];
var selector = 'ul li input[value="' + value + '"]')
var elem = $(selector);
if (elem) {
elem.prop("checked", true);
}
}
Or:
$('input[name^='+daily+']').prop("checked", function() {
return days.indexOf(this.value) > -1;
});
You can do it like,
var arr = ["2","3","4"];
var elems = $('input[name^='+daily+']');
arr.forEach(function(val){
elems.filter("[value="+ val +"]").prop("checked",true);
});
DEMO
Points to be noted:
Try to cache your selector outside the iteration phase, that would
improve the performance.
Iterating over all the elements and checking its value against the
array would cause severe performance drawback when you have 100+
elements and your array size is 2.
You could do this :
var days = [0, 2, 3];
var $checkboxes = $('input[name^=daily]');
days.forEach(function(day) {
$checkboxes.get(day).checked = true;
});
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<ul>
<li><input type="checkbox" name="daily[]" value="0"></li>
<li><input type="checkbox" name="daily[]" value="1"></li>
<li><input type="checkbox" name="daily[]" value="2"></li>
<li><input type="checkbox" name="daily[]" value="3"></li>
<li><input type="checkbox" name="daily[]" value="4"></li>
</ul>
(see also this Fiddle)
I am trying to implement a check box which checks all the check boxes on the page. But when I changed the code slightly, it stopped working. I want to keep the changed code and still want the functionality to be working. Kindly help!
* Kindly ignore the missing tags if any. It is correct unless I made mistake in editing the question.
<script>
function toggle(source) {
checkboxes = document.getElementsByName('qchecked[]');
for(var i=0, n=checkboxes.length;i<n;i++){
checkboxes[i].checked = source.checked;
}
}
</script>
<html>
/* Code for the check box which when checked, checks all the checkbox. */
<input type='checkbox' class='css-checkbox' id='checkbox' onClick='toggle(this)'/>
<label for='checkbox' class='css-label lite-y-green'></label>
/* Code for the check boxes which should be checked when the check box with id=checkbox is checked.
I changed the code from INITIAL CODE to CHANGED CODE for some other purpose and the toggle stopped working.
Now clicking on that one check box is not marking or un marking all the check boxes. */
<!-- INITIAL CODE -->
<input type='checkbox' id='yes_checkbox[$index]' class='css-checkbox' name='qchecked[]'/>
<label for='yes_checkbox[$index]' class='css-label lite-y-green'></label>
<!-- CHANGED CODE -->
<input type='checkbox' id='yes_checkbox[$index]' class='css-checkbox' name='qchecked[$array6[qID]]'/>
<label for='yes_checkbox[$index]' class='css-label lite-y-green'></label>
</html>
Instead of name, give a class to all elements and you should use by
getElementsByClassName('your_class');
Since you name of inputs are different, you can make use of common class
checkboxes = document.getElementsByClassName('css-checkbox');
Try this..
<ul class="chk-container">
<li><input type="checkbox" id="selecctall"/> Selecct All</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item1"> This is Item 1</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item2"> This is Item 2</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item3"> This is Item 3</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item4"> This is Item 4</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item5"> This is Item 5</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item6"> This is Item 6</li>
<li><input class="checkbox2" type="checkbox" name="check[]" value="item6"> Do not select this</li>
</ul>
$(document).ready(function() {
$('#selecctall').click(function(event) { //on click
if(this.checked) { // check select status
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
}
});
});
demo:https://jsfiddle.net/go1gL743/
AM trying to autoselect some on checkbox input based on radio button selection , Am able to do this stuff , but for my checklist am making use of check-tree plugin , when I tried to read input elements its not taking .......:(
Below is my code ,
<script>
$(function() {
$('.check-all').live('change', function(){
$('.options').find('input[class=def]').attr('checked', true);
return false;
});
$('.uncheck-all').live('change', function(){
$('.options').find('input[class=def]').attr('checked', false);
return false;
});
});
</script>
<script type="text/javascript">
var $checktree;
$(function(){
$checktree = $("ul.tree").checkTree();
});
</script>
<div id="main">
<div class="full_w" >
<div class="b2"><b>Define categories </b></div></div>
<div id="cat_left">
<div class="content">
</div>
<form action="http://localhost:8080/cgi-bin/cat_checkbox.pl" method="POST" name="form1">
<div class="options">
<ul>
<label><input type="radio" name="Selection" class="check-all" value="Default" id="type_0" checked="checked" />Default</label>
<label><input type="radio" name="Selection" class="uncheck-all" value="Custom" id="type_1" />Custom</label>
</ul>
<ul>
<li><input type="checkbox" class="def"id="option1" /><label for="option1">Option 1</label></li>
<li><input type="checkbox" class="def" id="option2" /><label for="option2">Option 2</label></li>
<li><input type="checkbox" class="def" id="option3" /><label for="option3">Option 3</label></li>
<li><input type="checkbox" class="def" id="option4" /><label for="option4">Option 4</label></li>
<li><input type="checkbox" id="option5" /><label for="option5">Option 5</label></li>
</ul>
// I tried till here its working fine, not able to do this same stuff foe below input elements
</div>
<ul class="tree">
<li><input type="checkbox"><label>Select All</label>
<ul>
<li><input class="cate" type='checkbox' class="def" name='v1' id='1' value='1'><label style=""; alt="">main1</label>
<ul>
<li><input type='checkbox' class="def" name='chk_0' value='1'><label>option1</label></li>
<li><input type='checkbox' class="def" name='chk_1' value='1'><label>option1</label></li>
</ul>
</li>
<li><input type='checkbox' name='' id='10' value='1'><label>main2</label>
<ul>
<li><input type='checkbox' name='' id='chk_7'' value='1'><label>option1</label></li>
<li><input type='checkbox' class="def" name='chk_4' id='chk_8' value='1'><label>option1</label></li>
<li><input type='checkbox' name='chk_5' id='chk_9' value='1'><label>option1</label></li>
</ul>
</li>
<li><input type='checkbox' name='' id='10' value='1'><label>main3</label>
<ul style="width: 90%">
<li><input type='checkbox' name='' id='chk_7'' value='1'><label>option1</label></li>
<li><input type='checkbox' name='chk_4' id='chk_8' value='1'><label>option1</label></li>
<li><input type='checkbox' name='chk_5' id='chk_9' value='1'><label>option1</label></li>
</ul>
</li>
</ul></li>
</ul>
</div>
<p><input type="submit" value="Submit"></p>
<INPUT type="hidden" SIZE=20 NAME="ip_adrress" value={{ ip }} >
</form>
And here is Checktree plugin
(function(jQuery) {
jQuery.fn.checkTree = function(settings) {
settings = jQuery.extend({
onExpand: null,
onCollapse: null,
onCheck: null,
onUnCheck: null,
onHalfCheck: null,
onLabelHoverOver: null,
onLabelHoverOut: null,
labelAction: "expand",
debug: false
}, settings);
var $tree = this;
$tree.find("li") // Hide all of the sub-trees
.find("ul:not(:first-child)").hide().end()// Hide all checkbox inputs
.find(":checkbox").change(function(){
var $all = jQuery(this).siblings("ul").find(":checkbox");
var $checked = $all.filter(":checked");
if($checked.length == 0) {
jQuery(this)
.attr("checked", "")
.siblings(".checkbox")
.removeClass("checked")
.removeClass("half_checked")
;
if (settings.onUnCheck) settings.onUnCheck(jQuery(this).parent());
}
else if ($all.length == $checked.length) {
jQuery(this)
.attr("checked", "checked")
.siblings(".checkbox")
.removeClass("half_checked")
.addClass("checked")
;
// Fire parent's onCheck callback
if (settings.onCheck) settings.onCheck(jQuery(this).parent());
}
// Some children are checked, makes the parent in a half checked state.
else {
// Fire parent's onHalfCheck callback only if it's going to change
if (settings.onHalfCheck && !jQuery(this).siblings(".checkbox").hasClass("half_checked"))
settings.onHalfCheck(jQuery(this).parent());
jQuery(this)
.attr("checked", "")
.siblings(".checkbox")
.removeClass("checked")
.addClass("half_checked")
;
}
})
.css("display", "none")
.end()
.each(function() {
// Go through and hide only ul's (subtrees) that do not have a sibling div.expanded:
// We do this to not collapse *all* the subtrees (if one is open and checkTree is called again)
jQuery(this).find("ul").each(function() {
if (!jQuery(this).siblings(".expanded").length) jQuery(this).hide();
});
// Copy the label
//var $label = jQuery(this).children("label").clone();
// Create or the image for the checkbox next to the label
var $checkbox = jQuery("<div class=\"checkbox\"></div>");
// Create the image for the arrow (to expand and collapse the hidden trees)
var $arrow = jQuery("<div class=\"arrow\"></div>");
var $cb = jQuery(this).children(":checkbox");
// If the li has children:
if (jQuery(this).is(":has(ul)")) {
// If the subtree is not visible, make the arrow collapsed. Otherwise expanded.
if (jQuery(this).children("ul").is(":hidden")) $arrow.addClass("collapsed");
else $arrow.addClass("expanded");
// When you click the image, toggle the child list
$arrow.click(function() {
jQuery(this).siblings("ul").toggle();
// Swap the classes: expanded <-> collapsed and fire the onExpand/onCollapse events
if (jQuery(this).hasClass("collapsed")) {
jQuery(this)
.addClass("expanded")
.removeClass("collapsed")
;
if (settings.onExpand) settings.onExpand(jQuery(this).parent());
}
else {
jQuery(this)
.addClass("collapsed")
.removeClass("expanded")
;
if (settings.onCollapse) settings.onCollapse(jQuery(this).parent());
}
});
}
// When you click the checkbox, it should do the checking/unchecking
if ($cb.attr("disabled"))
{
$checkbox.addClass("disabled");
}
else
{
$checkbox.click(function() {
// Toggle the checked class)
jQuery(this)
.toggleClass("checked")
// if it's half checked, its now either checked or unchecked
.removeClass("half_checked")
;
// Check/uncheck children depending on our status.
if (jQuery(this).hasClass("checked")) {
// Set the (real, hidden) checkbox to checked
jQuery(this).siblings(":checkbox").attr("checked", "checked");
// Fire the check callback for this parent
if (settings.onCheck) settings.onCheck(jQuery(this).parent());
// Go to the sibling list, and find all unchecked checkbox images
jQuery(this).siblings("ul").find(".checkbox").not(".checked").not(".disabled")
// Set as fully checked:
.removeClass("half_checked")
.addClass("checked")
// For each one, fire the onCheck callback
.each(function() {
if (settings.onCheck) settings.onCheck(jQuery(this).parent());
})
// For each one, check the checkbox (actual input element)
.siblings(":checkbox")
.attr("checked", "checked")
;
}
// If Unchecked:
else {
// Set the (real, hidden) checkbox to unchecked.
jQuery(this).siblings(":checkbox").attr("checked", "");
// Fire the uncheck callback for this parent
if (settings.onUnCheck) settings.onUnCheck(jQuery(this).parent());
// Go to the sibling list and find all checked checkbox images
jQuery(this).siblings("ul").find(".checkbox").filter(".checked").not(".disabled")
// Set as fully unchecked
.removeClass("half_checked")
.removeClass("checked")
// For each one fire the onUnCheck callback
.each(function() {
if (settings.onUnCheck) settings.onUnCheck(jQuery(this).parent());
})
// For each one, uncheck the checkbox (the actual input element)
.siblings(":checkbox")
.attr("checked", "")
;
}
// Tell our parent checkbox that we've changed (they might need to change their state)
jQuery(this).parents("ul").siblings(":checkbox").change();
});
}
// Add the appropriate classes to the new checkbox image based on the old one:
if (jQuery(this).children(".checkbox").hasClass("checked"))
$checkbox.addClass("checked");
else if (jQuery(this).children(":checkbox").attr("checked")) {
$checkbox.addClass("checked");
jQuery(this).parents("ul").siblings(":checkbox").change()
}
else if (jQuery(this).children(".checkbox").hasClass("half_checked"))
$checkbox.addClass("half_checked");
// Remove any existing arrows or checkboxes or labels
jQuery(this).children(".arrow").remove();
jQuery(this).children(".checkbox").remove();
//jQuery(this).children("label").remove();
// Prepend the new arrow, label, and checkbox images to the front of the LI
jQuery(this)
//.prepend($label)
.prepend($checkbox)
.prepend($arrow)
;
})
.find("label")
// Clicking the labels should do the labelAction (either expand or check)
.click(function() {
var action = settings.labelAction;
switch(settings.labelAction) {
case "expand":
jQuery(this).siblings(".arrow").click();
break;
case "check":
jQuery(this).siblings(".checkbox").click();
break;
}
})
// Add a hover class to the labels when hovering
.hover(
function() {
jQuery(this).addClass("hover");
if (settings.onLabelHoverOver) settings.onLabelHoverOver(jQuery(this).parent());
},
function() {
jQuery(this).removeClass("hover");
if (settings.onLabelHoverOut) settings.onLabelHoverOut(jQuery(this).parent());
}
)
.end()
;
return $tree;
};
})(jQuery);
Your $("ul.tree") is being executed before the DOM is fully loaded, jQuery can't see it. I believe that moving that piece of code to a onload event, or moving to the bottom of your DOM it will work.
Ok... I believe I got it now.
$('.check-all').live('change', function(){
$('.options').find('input[class=def]').attr('checked', true);
//This line should select the ones marked with the class ".def"
$('ul.tree').find('input.def').siblings("div.checkbox").click();
return false;
});
It's also worth noting that I re-downloaded the plugin from jquery-checktree.