Unchecked parent if child node is unchecked - javascript

I having problem on unchecked parent node if one of the child is unchecked. But i had try to search solution but none of the solution work on my code.
I refer the nested checkbox function here http://uoziod.github.io/deep-checkbox/
Here is example of my code:
<ul>
<li>
<label><input type="checkbox" data-id="All Master" data-name="All Master" id="myCheckBox0" onchange="checkDisabled(testing);"/> All Kedai Kiosk On Master Mode</label>
<ul>
<li>
<label><input type="checkbox" data-id="Terengganu" data-name="Terengganu" id="myCheckBox76" onchange="checkDisabled(testing);"/> Terengganu</label>
<ul id="navlist">
<li><label><input type="checkbox" data-id="Kiosk 63" data-name="Kiosk 63" id="myCheckBox77" onchange="checkDisabled(testing);"/> Kiosk 63</label></li>
<li><label><input type="checkbox" data-id="Kiosk 64" data-name="Kiosk 64" id="myCheckBox78" onchange="checkDisabled(testing);"/> Kiosk 64</label></li>
</ul>
</li>
</ul>
</li>
</ul>
What i want is tht when i unchecked kiosk 63 then the Terengganu which is parent also will be unchecked. I'm using the jquery.deepcheckbox.js that i download from the website too. What should i change in order to achieve that ? Thanks
Edit:
I copy the javascript code here. It there anything i need to change in order to achieve the parent uncheck function? thanks
Code Here:
(function ($) {
var defaults = {
listItemBefore: '<span class="item">',
listItemAfter: '</span>',
listItemsDivider: ', ',
labelExceptBefore: ' (except ',
labelExceptAfter: ')',
labelExceptBetween: ', ',
labelNothingIsSelected: 'Nothing is selected'
},
instances = [];
$.fn.deepcheckbox = function (options) {
if (instances.indexOf(this.selector) < 0) {
var tree = _buildTree(this);
_bindCheckboxes(tree, function (item, value) {
if (item.children) {
_setValueToChildren(item.children, value);
}
});
if (!options) {
options = {};
}
options = $.extend(defaults, options);
if (options.readableListTarget) {
$(options.readableListTarget).html(options.labelNothingIsSelected);
_bindCheckboxes(tree, function () {
var items = [],
except = [],
output = [];
function _dig (branch, level, skipAdding) {
if (!level) {
level = 0;
}
for (var i = 0, len = branch.length; i < len; i++) {
if (branch[i].el.prop('checked')) {
var value = options.listItemBefore.replace('{{id}}', branch[i].el.data('id')) + branch[i].el.data('name'),
exceptCount = 0;
if (branch[i].children) {
for (var j = 0, lenJ = branch[i].children.length; j < lenJ; j++) {
if (!branch[i].children[j].el.prop('checked')) {
except.push(branch[i].children[j].el.data('id'));
if (exceptCount === 0) {
value += options.labelExceptBefore;
}
if (exceptCount > 0) {
value += options.labelExceptBetween;
}
value += branch[i].children[j].el.data('name');
exceptCount++;
}
}
if (exceptCount > 0) {
value += options.labelExceptAfter;
}
}
value += options.listItemAfter;
if (level > 0 && branch[i].el.prop('checked') && !branch[i].parent.prop('checked')) {
skipAdding = false;
}
if (!skipAdding || exceptCount > 0) {
output.push(value);
items.push(branch[i].el.data('id'));
}
}
if (branch[i].children) {
_dig(branch[i].children, level + 1, true);
}
}
return output.join(options.listItemsDivider);
}
var digged = _dig(tree);
$(options.readableListTarget).html((digged.length > 0) ? digged : options.labelNothingIsSelected);
if (options.onChange && typeof options.onChange === 'function') {
options.onChange(items, except);
}
});
}
instances.push(this.selector);
}
};
function _buildTree ($anchor, $parent) {
var output = [],
rootItems = $anchor.find('ul:first > li');
for (var i = 0, len = rootItems.length; i < len; i++) {
var $element = $(rootItems[i]).find('input[type=checkbox]:first'),
id = _guId();
if (!$element.data('id')) {
$element.data('id', id);
}
if (!$element.data('name')) {
$element.data('name', id);
}
var branch = {
el: $element
},
children = _buildTree($(rootItems[i]), $element);
if (children) {
branch.children = children;
}
if ($parent) {
branch.parent = $parent;
}
output.push(branch);
}
return output.length > 0 ? output : false;
}
function _bindCheckboxes (tree, callback) {
for (var i = 0, len = tree.length; i < len; i++) {
(function (item) {
$(item.el).on('change', function () {
callback(item, $(this).prop('checked'));
});
if (item.children) {
_bindCheckboxes(item.children, callback);
}
}(tree[i]));
}
}
function _setValueToChildren (tree, value) {
for (var i = 0, len = tree.length; i < len; i++) {
tree[i].el.prop('checked', value);
if (tree[i].children) {
_setValueToChildren(tree[i].children, value);
}
}
}
function _guId () {
function s4 () {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
})(jQuery);
My test selected part:
<div>
<p>Selected items (readable): <span class="selected-readable"></span></p>
<p>Selected items: <span class="selected">[]</span></p>
<p>Excepted items: <span class="excepted">[]</span></p>
</div>

Please try this
$('ul :checkbox').bind('click', function () {
var $chk = $(this), $li = $chk.closest('li'), $ul, $parent ;
if($li.has('ul')){
$li.find(':checkbox').not(this).prop('checked', this.checked)
}
do{
$ul = $li.parent();
$parent = $ul.siblings(':checkbox');
if($chk.is(':checked')){
$parent.prop('checked', $ul.has(':checkbox:not(:checked)').length == 0)
} else {
$parent.prop('checked', false)
}
$chk = $parent;
$li = $chk.closest('li');
} while($ul.is(':not(.someclass)'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<ul class="parent-ul">
<li>
<input type="checkbox" data-id="All Master" data-name="All Master" id="myCheckBox0" onchange="checkDisabled(testing);" />All Kedai Kiosk On Master Mode
<ul>
<li>
<input type="checkbox" data-id="Terengganu" data-name="Terengganu" id="myCheckBox76" onchange="checkDisabled(testing);" />Terengganu
<ul id="navlist">
<li>
<input type="checkbox" data-id="Kiosk 63" data-name="Kiosk 63" id="myCheckBox77" onchange="checkDisabled(testing);" />Kiosk 63</li>
<li>
<input type="checkbox" data-id="Kiosk 64" data-name="Kiosk 64" id="myCheckBox78" onchange="checkDisabled(testing);" />Kiosk 64</li>
</ul>
</li>
</ul>
</li>
</ul>

I test it on ur page, its work!
$(document).ready(function(){
$('body').on('click', 'input[type="checkbox"]', function(){
$this = $(this)
var flag = true
$.each($this.closest('ul').find('input'), function(){
if ($(this).prop('checked') == false){
flag = false}
});
if(flag){
$this.closest('ul').closest('li').find('input').first().prop('checked', true);
if ($this.closest('ul').closest('li').closest('ul').closest('li').length > 0){
document.aa = $this.closest('ul').closest('li').closest('ul').closest('li').find('ul input')
$.each( $this.closest('ul').closest('li').closest('ul').closest('li').find('ul input'), function(){
if ($(this).prop('checked') == false){
flag = false}
});
if(flag){$this.closest('ul').closest('li').closest('ul').closest('li').find('input').first().prop('checked', true);}
}}
else{
parents = $this.parents('ul li');
parents.splice(0,1);
for (var i = 0; i < parents.length; i++) {
$this = $(parents[i]);
$this.find('label').first().find('input').prop('checked', false);
};
}
});
});

Related

Uncaught ReferenceError: Unable to process binding "visible: function (){return NeedPaging }" Message: NeedPaging is not defined

Uncaught ReferenceError: Unable to process binding "visible: function (){return NeedPaging }"
Message: NeedPaging is not defined
at visible (eval at parseBindingsString (knockout-3.4.2.js:68), :3:60)
at update (knockout-3.4.2.js:104)
at function.a.B.i (knockout-3.4.2.js:73)
at Function.Uc (knockout-3.4.2.js:52)
at Function.Vc (knockout-3.4.2.js:51)
at Function.U (knockout-3.4.2.js:51)
at Object.a.m.a.B (knockout-3.4.2.js:49)
at knockout-3.4.2.js:73
at Object.r (knockout-3.4.2.js:11)
at m (knockout-3.4.2.js:72)
I'm stuck any help would be great thank you in advance.
I'm only getting this error in production however in my local it is working just fine I'm not sure what I'm missing. It looks like the comment is being removed which is giving me the error.
$(function () {
"use strict";
var PagingVm = function (options) {
var self = this;
self.PageSize = ko.observable(options.pageSize);
self.CurrentPage = ko.observable(1);
self.TotalCount = ko.observable(options.totalCount);
self.PageCount = ko.pureComputed(function () {
return Math.ceil(self.TotalCount() / self.PageSize());
});
self.SetCurrentPage = function (page) {
if (page < self.FirstPage)
page = self.FirstPage;
if (page > self.LastPage())
page = self.LastPage();
self.CurrentPage(page);
};
self.FirstPage = 1;
self.LastPage = ko.pureComputed(function () {
return self.PageCount();
});
self.NextPage = ko.pureComputed(function () {
var next = self.CurrentPage() + 1;
if (next > self.LastPage())
return null;
return next;
});
self.PreviousPage = ko.pureComputed(function () {
var previous = self.CurrentPage() - 1;
if (previous < self.FirstPage)
return null;
return previous;
});
self.NeedPaging = ko.pureComputed(function () {
return self.PageCount() > 1;
});
self.NextPageActive = ko.pureComputed(function () {
return self.NextPage() != null;
});
self.PreviousPageActive = ko.pureComputed(function () {
return self.PreviousPage() != null;
});
self.LastPageActive = ko.pureComputed(function () {
return (self.LastPage() !== self.CurrentPage());
});
self.FirstPageActive = ko.pureComputed(function () {
return (self.FirstPage !== self.CurrentPage());
});
// this should be odd number always
var maxPageCount = 7;
self.generateAllPages = function () {
var pages = [];
for (var i = self.FirstPage; i <= self.LastPage(); i++)
pages.push(i);
return pages;
};
self.generateMaxPage = function () {
var current = self.CurrentPage();
var pageCount = self.PageCount();
var first = self.FirstPage;
var upperLimit = current + parseInt((maxPageCount - 1) / 2);
var downLimit = current - parseInt((maxPageCount - 1) / 2);
while (upperLimit > pageCount) {
upperLimit--;
if (downLimit > first)
downLimit--;
}
while (downLimit < first) {
downLimit++;
if (upperLimit < pageCount)
upperLimit++;
}
var pages = [];
for (var i = downLimit; i <= upperLimit; i++) {
pages.push(i);
}
return pages;
};
self.GetPages = ko.pureComputed(function () {
self.CurrentPage();
self.TotalCount();
if (self.PageCount() <= maxPageCount) {
return ko.observableArray(self.generateAllPages());
} else {
return ko.observableArray(self.generateMaxPage());
}
});
self.Update = function (e) {
self.TotalCount(e.TotalCount);
self.PageSize(e.PageSize);
self.SetCurrentPage(e.CurrentPage);
};
self.GoToPage = function (page) {
if (page >= self.FirstPage && page <= self.LastPage())
self.SetCurrentPage(page);
}
self.GoToFirst = function () {
self.SetCurrentPage(self.FirstPage);
};
self.GoToPrevious = function () {
var previous = self.PreviousPage();
if (previous != null)
self.SetCurrentPage(previous);
};
self.GoToNext = function () {
var next = self.NextPage();
if (next != null)
self.SetCurrentPage(next);
};
self.GoToLast = function () {
self.SetCurrentPage(self.LastPage());
};
}
var MainViewModel = function () {
var self = this;
self.PageSize = ko.observable(10);
self.AllData = ko.observableArray();
self.PagaData = ko.observableArray();
self.ActivePaging = ko.observable(false);
self.Paging = ko.observable(new PagingVm({
pageSize: self.PageSize(),
totalCount: self.AllData.length
}));
self.DeSelect = function (mainModel, event) {
if (event.target.value === self.SelectedSearchOption()) {
self.SelectedSearchOption(null);
event.target.checked = false;
}
return true;
};
self.pageSizeSubscription = self.PageSize.subscribe(function (newPageSize) {
self.Paging().Update({
PageSize: newPageSize,
TotalCount: self.AllData().length,
CurrentPage: self.Paging().CurrentPage()
});
self.RenderAgain();
});
self.currentPageSubscription = self.Paging().CurrentPage.subscribe(function () {
self.RenderAgain();
});
self.RenderAgain = function () {
var result = [];
var startIndex = (self.Paging().CurrentPage() - 1) * self.Paging().PageSize();
var endIndex = self.Paging().CurrentPage() * self.Paging().PageSize();
for (var i = startIndex; i < endIndex; i++) {
if (i < self.AllData().length)
result.push(self.AllData()[i]);
}
self.PagaData(result);
}
self.dispose = function () {
self.currentPageSubscription.dispose();
self.pageSizeSubscription.dispose();
}
}
var vm = new MainViewModel();
ko.applyBindings(vm);
vm.RenderAgain();
});
<div data-bind="visible: ActivePaging" class="row" style="display: none;">
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 form-group">
<label>page size</label>
<input class="form-control" type="number" min="1" data-bind="textInput:PageSize" />
</div>
<div class="col-sm-6">
<div class="form-group marg-top-reports">
<!-- ko with:Paging()-->
<ul data-bind="visible: NeedPaging" class="pull-left pagination">
<li data-bind="css: { disabled: !FirstPageActive() }">
<a data-bind="click: GoToFirst">First</a>
</li>
<li data-bind="css: { disabled: !PreviousPageActive() }">
<a data-bind="click: GoToPrevious">Previous</a>
</li>
<!-- ko foreach: GetPages() -->
<li data-bind="css: { active: $parent.CurrentPage() === $data }">
<a data-bind="click: $parent.GoToPage, text: $data"></a>
</li>
<!-- /ko -->
<li data-bind="css: { disabled: !NextPageActive() }">
<a data-bind="click: GoToNext">Next</a>
</li>
<li data-bind="css: { disabled: !LastPageActive() }">
<a data-bind="click: GoToLast">Last</a>
</li>
</ul>
<!-- /ko -->
</div>
</div>
</div>
</div>

Websockets draggable instead of onclick

I'm making a simple to-do list with WebSockets. The simple-todo is created but I only managed to create it with a click instead of the draggable option it should have. I changed the click to draggable but it didn't work. here is the code I used.
<!doctype html>
<html>
<head>
<title>Simple Todo</title>
</head>
<body>
TODO <input type="text" id="newTodoItem">
<ul id="itemsTodo">
</ul>
PROGRESS
<ul id="itemsProgress">
</ul>
DONE
<ul id="itemsDone">
</ul>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
/* statusses
0: todo
1: progress
2: done
*/
window.addEventListener('DOMContentLoaded', function () {
socket.emit("submitNewTodoItemMessage", {});
}, false);
// Checks if a new toto item is submitted
document.onkeyup = function (e) {
if (e.which === 13) {
var newTodoItem = {};
newTodoItem.id = parseFloat(new Date().getTime() + Math.random());
newTodoItem.status = 0;
newTodoItem.action = document.getElementById("newTodoItem").value;
if (newTodoItem !== '') {
socket.emit("submitNewTodoItemMessage", newTodoItem);
}
document.getElementById("newTodoItem").value = "";
}
};
socket.on("listOfAllTodoItemsMessage", function (listOfAllTodoItems) {
var itemsTodo = [], itemsProgress = [], itemsDone = [];
for (var i = 0; i < listOfAllTodoItems.length; i++) {
var item = listOfAllTodoItems[i];
var dragItem = "<li>" + item.action + " <span class='changeStatus' id='p_" + item.id + "'>^</span> <span class='changeStatus' id='n_" + item.id + "'>v</span></li>";
if (listOfAllTodoItems[i].status === 0) {
itemsTodo.push(dragItem);
} else if (listOfAllTodoItems[i].status === 1) {
itemsProgress.push(dragItem);
} else if (listOfAllTodoItems[i].status === 2) {
itemsDone.push(dragItem);
}
document.getElementById('itemsTodo').innerHTML = itemsTodo.join("");
document.getElementById('itemsProgress').innerHTML = itemsProgress.join("");
document.getElementById('itemsDone').innerHTML = itemsDone.join("");
}
$(".changeStatus").draggable(function (e) {
socket.emit("submitStatusUpdateTodoItemMessage", e.target.id);
});
$(".changeStatus").css('cursor', 'pointer');
});
</script>
</body>
</html>
the code snippet is now on the draggable state but it isn't working. I'm using jquery so the draggable function should work I guess.

change text color of matching text from input in javascript

Here is my code
And I am trying to change the color of any match in the <li> elements that matches the text in the <input> element. So if you type lets say "this is a simple text" the result should look like this:
<input value="this is a simple text" id="term"/>
<ul id="ul-id" >
<li id="li-id-1"> hello budy <span style="color:red">this</span> <span style="color:red">is</span> really <span style="color:red">simple</span> stuff </li>
<li id="li-id-2"> <span style="color:red">this</span> <span style="color:red">is</span> it</li>
<li id="li-id-3"> there <span style="color:red">is</span> something here</li>
<li id="li-id-4"> plain <span style="color:red">text</span> file</li>
</ul>
Any help would be appreciated.
Thank you.
You can remove the delay function if you like, but this would lead to a performance loss:
// https://stackoverflow.com/a/9310752/1636522
RegExp.escape = function (text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
};
window.addEventListener('load', function () {
var wrapper = '<span style="background:yellow">$&</span>';
var input = document.getElementById('term');
var list = document.getElementById('ul-id');
var items = list.getElementsByTagName('li');
var l = items.length;
var source = Array.prototype.map.call(
items, function (li) { return li.textContent; }
);
var cmp = function (a, b) {
return b.length - a.length;
};
var delay = function (fn, ms) {
var id, scope, args;
return function () {
scope = this;
args = arguments;
id && clearTimeout(id);
id = setTimeout(function () {
fn.apply(scope, args);
}, ms);
};
};
term.addEventListener('keyup', delay(function () {
var i, re, val;
if (val = this.value.match(/[^ ]+/g)) {
val = val.sort(cmp).map(RegExp.escape);
re = new RegExp(val.join('|'), 'g');
for (i = 0; i < l; i++) {
items[i].innerHTML = source[i].replace(re, wrapper);
}
}
else {
for (i = 0; i < l; i++) {
items[i].textContent = source[i];
}
}
}, 500));
});
<input value="" id="term"/>
<ul id="ul-id" >
<li id="li-id-1"> hello budy this is really simple stuff </li>
<li id="li-id-2"> this is it</li>
<li id="li-id-3"> there is something here</li>
<li id="li-id-4"> plain text file</li>
</ul>
Similar topic: https://stackoverflow.com/a/20427785/1636522.
I don't know if it is possible with only RegEx, but here is a jQuery solution:
$('#term').change(function() {
var inpArr = $(this).val().split(" ");
$('#ul-id li').each(function() {
var liArr = $(this).text().split(" ");
var txt = "";
$.each(liArr, function(i, v) {
if(inpArr.indexOf(v) > -1) {
txt += "<span class='red'>"+ v +"</span> ";
} else {
txt += v + " ";
}
});
$(this).html(txt);
});
});
span.red {
color: red;
}
And the working fiddle: https://jsfiddle.net/ermk32yc/1/
Plain JS solution
var list = document.querySelector('#ul-id'),
listItem,
listItems,
term = document.querySelector('#term'),
oldRef = list.innerHTML,
oldValue;
term.addEventListener('keyup', function () {
var regExp,
value = term.value;
if (oldValue !== value) {
oldValue = value;
// Reset
list.innerHTML = oldRef;
if (value.trim() !== '') {
listItems = list.querySelectorAll('#ul-id li');
regExp = new RegExp(term.value, 'g');
// Perform matching
for (var i = 0; i < listItems.length; i++) {
listItem = listItems[i];
listItem.innerHTML = listItem.innerHTML.replace(regExp, function (match) {
return '<span class="matched">' + match + '</span>';
});
}
}
}
}, false);
.matched {
color: red;
}
<input id="term"/>
<ul id="ul-id" >
<li id="li-id-1"> hello budy this is really simple stuff </li>
<li id="li-id-2"> this is it</li>
<li id="li-id-3"> there is something here</li>
<li id="li-id-4"> plain text file</li>
</ul>
You might do something like this
$('#term').change(function (i) {
var terms = $('#term').val().split(" ");
$('#ul-id > li').each(function (i, el) {
var val = $(el).html().replace(/<[^<]+>/g, ''),
match;
terms.forEach(function (term) {
val = val.replace(new RegExp(term, 'g'),
'<span style="color:red">' + term + '</span>');
});
$(el).html(val);
});
});
https://jsfiddle.net/1vm0259x/5/
You can use the below solution if there is no html contents in the li elemnets
if (!RegExp.escape) {
RegExp.escape = function(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
var lis = [].slice.call(document.querySelectorAll('#ul-id li'));
lis.forEach(function(el) {
el.dataset.text = el.innerHTML;
});
document.querySelector('#term').addEventListener('change', function() {
var parts = this.value.split(' ').map(function(value) {
return '\\b' + RegExp.escape(value) + '\\b';
});
var regex = new RegExp(parts.join('|'), 'g');
lis.forEach(function(el) {
el.innerHTML = el.dataset.text.replace(regex, function(part) {
return '<span class="highlight">' + part + '</span>'
})
});
});
.highlight {
color: red;
}
<input id="term" />
<ul id="ul-id">
<li id="li-id-1">hello budy this is really simple stuff</li>
<li id="li-id-2">this is it</li>
<li id="li-id-3">there is something here</li>
<li id="li-id-4">plain text file</li>
</ul>
With jQuery
if (!RegExp.escape) {
RegExp.escape = function(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
$('#term').on('change keyup', function() {
//$('#ul-id li .highlight').contents().unwrap();//remove previous highlights
var parts = this.value.split(' ').map(function(value) {
return '\\b' + RegExp.escape(value) + '\\b';
});
var regex = new RegExp(parts.join('|'), 'g');
$('#ul-id li ').each(function() {
var text = $(this).text();
$(this).html(text.replace(regex, function(part) {
return '<span class="highlight">' + part + '</span>'
}))
})
});
.highlight {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="term" />
<ul id="ul-id">
<li id="li-id-1">hello budy this is really simple stuff</li>
<li id="li-id-2">this is it</li>
<li id="li-id-3">there is something here</li>
<li id="li-id-4">plain text file</li>
</ul>
you can handle blur event or you can copy paste the inner function code to wherever it is required. this is the guide code here you can more explore match function as per your requirement and then can traverse your li elements as shown below.
$('#term).blur(function() {
$('#ul-id li').foreach(function()
{
if($(this).text().match($("#term").text()))
{
///set/change here color of li element
$(this).css('color', 'red');
}
}
}

Checkbox variable outside of function

I am new to coding (trying to learn) and I cant figure out how to get the var of the check box value outside of the function.
Javascript:
$(document).ready(function() {
var quantity= parseInt($('#phones').val());
$("#check1 input:checkbox").change(function() {
var feature = 0;
$("#check1 input:checkbox").each(function() {
if ($(this).is(':checked')) {
feature += parseInt($(this).prop('value'));
}
});
});
var grand = feature * (quantity * Number ('0.1'))
var total = quantity + grand
});
HTML:
<input id="phones" type="numerical" value="0" style="text-align: right"/>
<div id="check1">
<input type="checkbox" value="1" />
function getResult(feature, phones) {
if (feature <= 0 || phones <= 0) {
return 'Error...., enter the number of phones and check some checkbox';
}
return (feature * (+phones * 0.1)) + +phones;
}
function getFeature() {
var feature = 0;
$('#check1 input:checkbox:checked').each(function () {
feature += +$(this).prop('value') || 1;
});
return feature;
}
$(document).ready(function() {
var $phones = $('#phones'),
$result = $('#result');
$("#check1 input:checkbox").change(function() {
$result.html(getResult(getFeature(), $phones.val()));
});
$("#phones").keyup(function() {
$result.html(getResult(getFeature(), $phones.val()));
});
});
Demo: http://jsbin.com/hivilu/2/

jQuery - list input classess and get number of selected checkboxes

I'm looking for jQuery code which will list all classess from inputs and display how many times every class (in this case class=value) is selected.
html schema:
<input type="checkbox" name="t1" class="a1" value="a1">
<input type="checkbox" name="t1" class="a2" value="a2">
<input type="checkbox" name="t1" class="a3" value="a3">
<input type="checkbox" name="t2" class="a1" value="a1">
<input type="checkbox" name="t2" class="a2" value="a2">
<input type="checkbox" name="t2" class="a3" value="a3">
...
<input type="checkbox" name="t9" class="a99" value="a99">
example of expected result:
a1 - 2
a2 - 0
a3 - 0
a99 - 0
Try
var map = {};
$('input[type=checkbox]').each(function () {
if (this.checked) {
map[this.className] = (map[this.className] || 0) + 1;
} else {
map[this.className] = map[this.className] || 0;
}
});
console.log(map)
Demo: Fiddle
You could try something like this:
var checked = new Array();
$("input[type=checkbox]").each( function() {
var cl = $(this).attr('class');
if (typeof(checked[cl]) == "undefined") checked[cl] = 0;
if ($(this).is(':checked')) checked[cl]++;
});
After this, you will have variable checked containing all checkbox classes, with number of checked boxes for each class.
Let me know if this works for you.
Fiddle: http://jsfiddle.net/smBSw/1/
var resultList = {}
$('input:checkbox').each(function () {
var result = resultList[this.className] || 0;
if (this.checked) {
result++;
}
resultList[this.className] = result;
});
console.log(resultList)
console.log(JSON.stringify(resultList));
You can use like :
var className = [];
$("#btn").click(function () {
$("#result").html("");
$("input[class^=a]").each(function () {
className.push($(this).attr("class"));
});
className = jQuery.unique(className);
for (i = 0; i < className.length; i++) {
var count = 0;
$("." + className[i]).each(function () {
if (this.checked) {
count++;
}
});
$("#result").append(
"<br/><span> " +
"className: " + className[i] + ", " +
"count :" + count +
"</span>"
);
}
});
demo fiddle
Basically you will need to iterate through these inputs.. but you will need a place to save the counts
$(".checkboxes").on("change", "input", function() {
var results = {"a1": 0, "a2": 0, "a3": 0};
$(".checkboxes input").each(function(i, checkbox) {
if (!$(checkbox).prop("checked")) {
return;
}
results[$(checkbox).val()] = results[$(checkbox).val()] + 1;
});
var resultsToAppend = '';
$.each(results, function(key, value) {
resultsToAppend += '<li>' + key + ' : ' + value + '</li>';
});
$(".results").html(resultsToAppend);
});
Here's a fiddle

Categories