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
Related
When I click the button jQuery append new input inside the div like below:
$('#addIndirectCityBtn').click(function () {
var inputs = $("#additionalCityInputs input").length
if (inputs <= 3) {
$('#additionalCityInputs').append('<input type="text" placeholder="Miasto" class="form-control" style="margin-bottom: 5px;" />')
}
})
How I can add uniqe ID to each new input?
Fore example id="new1" for the second one id="new2" and so on.
Any ideas?
$('#addIndirectCityBtn').click(function () {
var inputs = $("#additionalCityInputs input").length
if (inputs <= 3) {
var newId = 'newId'+(inputs + 1);
$('#additionalCityInputs').append('<input id="'+newId+'" type="text" placeholder="Miasto" class="form-control" style="margin-bottom: 5px;" />')
}
})
Try:
var counter = 0;
$('#addIndirectCityBtn').click(function () {
var inputs = $("#additionalCityInputs input").length
if (inputs <= 3) {
$('#additionalCityInputs').append('<input id="new' + ++counter + '" type="text" placeholder="Miasto" class="form-control" style="margin-bottom: 5px;" />')
}
})
use an IFFE
(function(){
var a = 0;
$('#addIndirectCityBtn').click(function () {
var inputs = $("#additionalCityInputs input").length
if (inputs <= 3) {
$('#additionalCityInputs').append('<input id="new'+ ++a + '" type="text" placeholder="Miasto" class="form-control" style="margin-bottom: 5px;" />')
}
})
}());
Use some counter variable to achieve this.
var i=0;
$('#addIndirectCityBtn').click(function () {
var inputs = $("#additionalCityInputs input").length;
i++;
if (inputs <= 3) {
$('#additionalCityInputs').append("<input id='new"+i+"' type='text' placeholder='Miasto' class='form-control' style='margin-bottom: 5px;' />");
}
});
If I have the following HTML on a page:
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
I would like to select the items using JavaScript (or JQuery) in such a way that I can loop over the items using the outer array.
Currently I have the following JQuery/JavaScript to handle the items:
var items = ($('[name*="item["]'));
var i = 0;
while (i < items.length) {
if (items[i++].value === '') {
// No ID set.
}
else if (items[i++].value === '') {
// No title set.
}
else if (items[i++].value === '') {
// No description set.
}
}
Is there a way to select the elements so that I can loop over them using notation more like the following (Where items.length is 3)?
for (var i = 0; i < items.length; i++) {
if (items[i][0].value === '') {
// No ID set.
}
else if (items[i][1].value === '') {
// No title set.
}
else if (items[i][2].value === '') {
// No description set.
}
}
Or even more like this?
for (var i = 0; i < items.length; i++) {
if (items[i].id.value === '') {
// No ID set.
}
else if (items[i].title.value === '') {
// No title set.
}
else if (items[i].description.value === '') {
// No description set.
}
}
Or would this require more manipulation and processing to go from selecting from the DOM to creating the data structure to loop over?
I think this is exactly what you are looking for (which is not really related to selectors):
function serialize () {
var serialized = {};
$("[name]").each(function () {
var name = $(this).attr('name');
var value = $(this).val();
var nameBits = name.split('[');
var previousRef = serialized;
for(var i = 0, l = nameBits.length; i < l; i++) {
var nameBit = nameBits[i].replace(']', '');
if(!previousRef[nameBit]) {
previousRef[nameBit] = {};
}
if(i != nameBits.length - 1) {
previousRef = previousRef[nameBit];
} else if(i == nameBits.length - 1) {
previousRef[nameBit] = value;
}
}
});
return serialized;
}
console.log(serialize());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
See the related JSFiddle sample.
Here's a way to add a custom function into JQuery to get the data structure you're looking for.
$.fn.getMultiArray = function() {
var $items = [];
var index = 0;
$(this).each(function() {
var $this = $(this);
if ($this.attr('name').indexOf('item[' + index + ']') !== 0)
index++;
if (!$items[index])
$items[index] = {};
var key = $this.attr('name').replace('item[' + index + '][', '').replace(']', '');
$items[index][key] = $this;
});
return $items;
};
var $items = $('input[name^="item["]').getMultiArray();
This allows you to have the references in your "ideal" example.
var $items = $('input[name^="item["]').getMultiArray();
$items[0].id;
JS Fiddle: https://jsfiddle.net/apphffus/
good day to all, i have this script where i am appending checkbox when the add button is click. now my problem is that when i add two checkbox, when i click the second checkbox it triggers the first checkbox not the second checkbox.
here's my code.
$(document).ready(function () {
var TempCounter = parseInt($('input[name^="TempID"]').val());
var count = TempCounter;
var ajaxCount = count + 1;
var reqCount = TempCounter;
$('#addButton').click(function(e) {
$("#ApprovalRequestor").append('<div><input style="margin-left:20px;" type="checkbox" id="requestorManagerChecked'+count+'" name="requestorManager['+count+']" > </input>'
+ '<span>'+document.getElementById(document.getElementById('selectOtherRequestor').value).innerHTML+'</span>Delete <input type="hidden" value="'+$('#selectOtherRequestor').val()+'" id="ApproversID" name="ApproversID['+count+']"> </input>'
+ '<input type="hidden" id="TempCount" name="TempCount" value="'+count+'"/>'
+ '<input type="hidden" id="levelID" name="levelID['+count+']" value="1"> </input> </div>');
$('#requestorManagerChecked'+count+' ').change(function() {
if($('#requestorManagerChecked'+reqCount+' ').is(":checked") ) {
$('#requestorManagerChecked'+reqCount+' ').val(1);
alert('requestorManagerChecked'+reqCount+' ');
alert($('#requestorManagerChecked'+reqCount+' ').val() );
}
else {
$('#requestorManagerChecked'+reqCount+' ').val(0);
alert($('#requestorManagerChecked'+reqCount+' ').val() );
}
});
$.ajax({
type: 'post',
url: 'mis.php/fileApproversListController/getCounter',
data: 'variable='+ajaxCount,
success: function(data) {
$('#Count').html(data);
}
});
reqCount = count;
ajaxCount++;
count++;
});
here's my controller
function SaveApprovers() {
$this->load->model('new_development_model');
$requestType = $this->input->post('requestTypeID');
$ApproversLists = $this->input->get_post('Approvers');
for($ctr = 0; $ctr <= $this->input->get_post('counter'); $ctr++) {
$ApproversLists[$ctr]['ApproversLevel'];
$ApproversLists[$ctr]['Required'];
$ApproversLists[$ctr]['ApproversID'];
$Remark = $this->input->get_post('Remarks');
$this->new_development_model->ApproversList($ApproversLists[$ctr]['ApproversLevel'], $ApproversLists[$ctr]['Required'],$ApproversLists[$ctr]['ApproversID'],$Remark);
}
}
How to check value in input using getElementsByClassName , Like this ?
When i load page, I want to alert
HAVE VALUE 3 INPUT
NOT HAVE VALUE 2 INPUT
How can i do that ?
................................................................................................................................................
http://jsfiddle.net/3AaAx/37/
<input type="text" class="xxx" value="111"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="222"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="333"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
// this function for use getElementsByClassName on IE 7 and 8 //
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', #class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
var xxx_var = document.getElementsByClassName('xxx');
alert(xxx_var.length);
});
</script>
Add below code after var xxx_var = document.getElementsByClassName('xxx');
var inputCount=0,nonInputCount=0;
for(var i=0;i<xxx_var.length;i++){
if(xxx_var[i].value != ""){
inputCount++;
}else{
nonInputCount++;
}
}
alert("Input Count " + inputCount + " , and non input count " +nonInputCount );
If you use jquery it will be very easier code.
Let me know if you didn't understand.
Thanks
Raviranjan
i've written this script to check when checkboxes with classes "A", "B" and "C" are selected and then add them together (these classes are assigned to multiple checkboxes). however, i want to only count one instance of them being checked, whereas this script counts them everytime checkboxes with these values are checked. how can i alter it to only count them once only?
jquery:
$(function() {
$('#product-counter .counter').text('0');
var total = $("#search-id-checkboxes .A:checked").length + $("#search-id-checkboxes .B:checked").length + $("#search-id-checkboxes .C:checked").length;
if(total>0){$("#product-counter .counter").text(total);}
else{$("#product-counter .counter").text('0');}
})
function updateCounter() {
var len = $("#search-id-checkboxes .A:checked").length + $("#search-id-checkboxes .B:checked").length + $("#search-id-checkboxes .C:checked").length;
if(len>0){$("#product-counter .counter").text(len);}
else{$("#product-counter .counter").text('0');}
}
$("#search-id-checkboxes input:checkbox").on("change", function() {
updateCounter();
});
html:
<div id="search-id-checkboxes">
<input type="checkbox" class="A"/> A<br />
<input type="checkbox" class="A" /> A<br />
<input type="checkbox" class="B" /> B<br />
<input type="checkbox" class="B" /> B<br />
<input type="checkbox" class="C" /> C<br />
<input type="checkbox" class="C" /> C<br />
</div>
you already tried the unique method of jquery?
See http://api.jquery.com/jQuery.unique/
Improvised logic to not have an iterate and work on the total that was calculated inside ready,
DEMO: http://jsfiddle.net/MQhyt/
Full function:
$(function () {
$('#product-counter .counter').text('0');
var inArray = [];
$("#search-id-checkboxes :checkbox").each(function () {
if (this.checked && $.inArray(this.className, inArray) == -1) {
inArray.push(this.className);
}
});
var total = inArray.length;
if (total > 0) {
$("#product-counter .counter").text(total);
} else {
$("#product-counter .counter").text('0');
}
$("#search-id-checkboxes input:checkbox").on("change", function () {
updateCounter.call(this);
});
function updateCounter() {
var elClass = this.className;
var $el = $('#search-id-checkboxes .' + elClass + ':checked');
if ($el.length == 1 && this.checked) {
total += 1;
} else if ($el.length == 0) {
total -= 1;
}
$("#product-counter .counter").text(total);
}
});
Check out this version http://jsfiddle.net/WLmtq/ using .each if you have any issues with above logic.
May be you want to check like below,
var len = ($("#search-id-checkboxes .A").is(":checked") ? 1 : 0) +
($("#search-id-checkboxes .B").is(":checked") ? 1 : 0) +
($("#search-id-checkboxes .C").is(":checked") ? 1 : 0);
DEMO: http://jsfiddle.net/MCKtA/
Use this...
var total = 0;
$(':checkbox').on('change', function (e) {
var a = $(this).prop('class');
if($("." + a + ':checked').length == 1 && $(this).is(':checked')){
total +=1;
}
if($("." + a + ':checked').length == 0){
total-=1;
}
$('#product-counter .counter').text(total);
});
See this DEMO