count checkbox class only once - javascript

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

Related

Multiple validation for same value in Jquery

I have this code to validate 2 input text, but how can I validate same input for
dynamic intput text ? meaning input text quantity can be up to 100 or more.
<input type="text" id="id1" />
<input type="text" id="id2" />
$('input').blur(function() {
if ($('#id1').attr('value') == $('#id2').attr('value')) {
alert('Same Value');
return false;
} else { return true; }
});
If you want to check all the inputs are the same (I gather that's what you're trying to do) you could just loop through them by using a function like this:
function validate() {
for (var i = 2; i <= 100; i++) {
if ($('#id' + x).val() !== $('#id' + (x - 1)).val()) {
return false;
}
}
return true;
}
Of course, you may want to create inputs themselves using a loop too if you'll have that many on the page.
<input type="text" id="id1" onblur="validate()">
<input type="text" id="id2" onblur="validate()">
<p style="display: none">Test</p>
<script type="text/javascript">
function validate() {
for (var i = 1; i <= 2; i++) {
if ($('#id' + i).val() == $('#id' + (i - 1)).val()) {
$( "p" ).show( "slow" ); return false;
}
else
{
$( "p" ).hide( 1000 );
}
}
return true;
}
</script>
What I did is this hope someone can you this in future reference

check box checked on page load and show output

Below is my working code but the only problem is, I want the check box to checked by default and show the jquery output on page load but it only show output when i re-check the check box.
http://jsfiddle.net/pratyush141/2mq5sr1h/
$(function() {
$defaultValue = $('.total').val();
$("input[type=checkbox]").click(function(event) {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('.total').val($defaultValue);
} else {
$('.total').val('$' + total);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="invoice">
<input type="checkbox" checked='checked' value="1" />
<span class="inv-total">$100</span>
</div>
<input type="text" class="total" value="$90" />
It's simple, just remove the checked=checked from the checkbox, then use jquery to call the click on checkbox
<div class="invoice">
<input type="checkbox" value="1" />
<span class="inv-total">$100</span>
</div>
$(function () {
$defaultValue = $('.total').val();
$("input[type=checkbox]").change(function (event) {
var total = 0;
$("input:checked").each(function () {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('.total').val($defaultValue);
} else {
$('.total').val('$' + total);
}
});
//Call the click on checkbox
$("input[type=checkbox]").click();
})
Working fiddle: http://jsfiddle.net/2mq5sr1h/5/
You set value of input on click event. You need to set it in $(document).ready(). Try to change your script to this:
$(document).ready(function (){
setValue();
$("input[type=checkbox]").click(function(event) {
setValue();
});
});
function setValue()
{
$defaultValue = $('.total').val();
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('.total').val($defaultValue);
}
else {
$('.total').val('$' + total);
}
}

How can I show a dollar sign before the amount value when the checkbox is checked?

When the checkbox is not checked it will show $0.00.
When I check the checkbox, it will show 1.00. I want it to show $1.00. How can I do that?
Demo on JS Fiddle
This is the code:
<form id="form1" method="post">
<input type="text" id="totalcost" value="$0.00">
<input type="checkbox" value="aa_1">
<input type="checkbox" value="aa_2">
<input type="checkbox" value="aa_3">
</form>
<script type="text/javascript">
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
var val = thisInput.value, // "bgh_9.99"
split_array = val.split("_"), // ["bgh", "9.99"]
pay_out_value = split_array[1]; // "9.99"
sum += parseFloat(pay_out_value); // 9.99
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
var val = thisInput.value, // "bgh_9.99"
split_array = val.split("_"), // ["bgh", "9.99"]
pay_out_value = split_array[1]; // "9.99"
sum -= parseFloat(pay_out_value); // 9.99
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "$0.00";
}
}
return null;
}());
</script>
Simply change this line:
totalcost.value = (sum > 0) ? sum.toFixed(2) : "$0.00";
to
totalcost.value = (sum > 0) ? "$" + sum.toFixed(2) : "$0.00";
^
This will add $ before your price !
FIDDLE
Just append the $ to the value:
totalcost.value = (sum > 0) ? '$' + sum.toFixed(2) : "$0.00";
Fiddle

Getting values from elements added dynamically

http://jsfiddle.net/R89fn/9/
If any of the text input/Box added are empty then the page must not submit.when I try to retrieve values from the text inputs using their id`s nothing gets retrieved is it possible to retrieve values from elements added dynamically?
$("#submit").click(function (event) {
var string = "tb";
var i;
for (i = 1; i <= count; i++) {
if (document.getElementById(string+1).value=="") {
event.preventDefault();
break;
}
}
});
The above code is what I am using to get the value from the text fields using there id
I took a look on the code in the JSFiddle. It appears that the input textboxes are not given the intended IDs; the IDs are given to the container div.
The code for the add button should use this,
var inputBox = $('<input type="text" id="td1">') //add also the needed attributes
$(containerDiv).append(inputBox);
Check out this solution on fiddle: http://jsfiddle.net/R89fn/15/
var count = 0;
$(document).ready(function () {
$("#b1").click(function () {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$('#form').append("<div class=\"newTextBox\" id=" + tb + ">" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function () {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function (event) {
var inputBoxes = $('#form').find('input[type="text"]');;
if (inputBoxes.length < 1) {
alert('No text inputs to submit');
return false;
} else {
inputBoxes.each(function(i, v) {
if ($(this).val() == "") {
alert('Input number ' + (i + 1) + ' is empty');
$(this).css('border-color', 'red');
}
});
alert('continue here');
return false;
}
});
});
<form name="form" id="form" action="htmlpage.html" method="POST">
<input type="button" id="b1" name="b1" value="Add TextBox" />
<input type="button" id="b2" name="b2" value="Remove TextBox" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
var count = 0;
$(document).ready(function() {
$("#b1").click(function() {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$(this).before("<div class=\"newTextBox\" id= "+ tb +" >" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function() {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function(event) {
var string = "#texttb";
var i;
for (i = 1; i <= count; i++) {
if ($('input[type = text]').val() == "") {
event.preventDefault();
break;
}
}
});
});
</script>
<style>
.newTextBox
{
margin: 5px;z
}
</style>
Reason:
you had given id to the div element. so its not get retrive. i had updated the answer with the usage of jquery functions and changed your code for this requirement.
If I understand correctly, your only issue atm is to make sure that the form is not sent if one of the inputs are empty? Seems the solution to your problem is simpler. Simply add required at the end of any input and HTML5 will ensure that the form is not sent if empty. For example:
<input type="text" required />

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