Jquery checkbox function get ID based on biggest data - javascript

I'm having trouble finding the jquery checkbox function to get the ID based on the largest data. The selected data, of course, is clicked and checked, not unchecked.
HTML:
<input type="checkbox" class="checkbox" name="id[]" data-id="001" data-weight="10" value="001"/> A (10 kg) <br>
<input type="checkbox" class="checkbox" name="id[]" data-id="002" data-weight="20" value="002"/> B (20 kg) <br>
<input type="checkbox" class="checkbox" name="id[]" data-id="003" data-weight="30" value="003"/> C (30 kg) <br>
<input type="checkbox" class="checkbox" name="id[]" data-id="004" data-weight="40" value="004"/> D (40 kg) <br>
<br>
<br>
<div>Heaviest Weight</div>
<input type="text" id="getWeight">
<div>ID the Heaviest Weight</div>
<input type="text" id="getId"><br>
Javascript:
$(document).ready(function() {
var maximum = null;
$(".checkbox").click(function(){
var value = $(this).data('weight');
maximum = (value > maximum) ? value : maximum;
id = $(this).data('id');
$('#getId').val(id);
$('#getWeight').val(maximum);
});
});
https://codepen.io/andreasdan/pen/MWvVypm

Try looping all checked checkbox, and compare each weight, every change of each checkbox.
$(document).ready(function() {
$(".checkbox").change(function(){
var checkboxes = document.querySelectorAll(".checkbox:checked");
var maximum = 0;
var maximumID = 0;
checkboxes.forEach(checkbox => {
var value = $(checkbox).data('weight');
if( value > maximum ){
maximum = value;
maximumID = $(checkbox).data('id');
}
});
$('#getId').val(maximumID);
$('#getWeight').val(maximum);
});
});

Related

how to calculate the total of two incremented values from two different loops?

I have a function that calculates sum of input values. In this form I have checkboxes and number type inputs. I'm able to make this function work with either only checkboxes or textboxes but not both at the same time. The two input types enter in conflict. It's probably very trivial but I can't seem to figure it out. Any help?
js
$(document).on("change", ".calculate", function () {
calculateTotal();
});
function calculateTotal() {
//input type number
var textboxsum = 0;
//input type checkbox
var addonsum = 0;
//iterate through each input
$(".calculate").each(function () {
//get input type
var type = this.getAttribute("data-type");
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
if (type === "room") {
//add amount $35 per room
var amount = parseFloat(this.value * 35);
} else if (type === "addon") {
var input = document.getElementsByName("checkbox");
for (var i = 0; i < input.length; i++) {
if (this.checked) {
//10$ per addon
addonsum += parseFloat(this.value * 10);
}
}
}
textboxsum += parseFloat(amount);
}
});
//addup the two totals
var totalAmount = textboxsum + addonsum;
//.toFixed() roundoff to 2 decimal
$(".total_amount").html(totalAmount.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>
Total : <span class="total_amount"></span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>
Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
there are few issues in the code, and you can use parseInt instead of parseFloat
$('.calculate').change(function() {
let amount = 0;
$(".calculate").each(function() {
const type = this.getAttribute('data-type');
if (!isNaN(this.value) && this.value.length !== 0) {
if (type === 'room') {
//add amount $35 per room
amount = parseInt(this.value, 10) * 35;
} else if (type === 'addon' && this.checked) {
amount += parseInt(this.value, 10) * 10;
}
}
});
$(".total_amount").html(amount.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>
Total : <span class="total_amount">0</span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>
Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
You have to declare var amount = 0; at top inside .each(). The reason you are getting NaN when type is not room then it will not execute code from if(type==='room') where you have declared amount and in end you have used textboxsum += parseFloat(amount);, so here amount will return undefined & textboxsum will become NaN.
Try it below.
$(document).on('change', '.calculate', function() {
calculateTotal();
});
function calculateTotal() {
//from input type number
var textboxsum = 0;
//from input type checkbox
var addonsum = 0;
//iterate through each textboxes and add the values
$(".calculate").each(function() {
//get input type
var type = this.getAttribute('data-type');
// declare amount variable here
var amount = 0; // <-- Change
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
if (type === 'room') {
//add amount $35 per room
// do not declare variable here. just use it
amount = parseFloat((this.value) * 35);
} else
if (type === 'addon') {
var input = document.getElementsByName("checkbox");
for (var i = 0; i < input.length; i++) {
if (this.checked) {
//10$ per addon
addonsum += parseFloat((this.value) * 10);
}
}
}
textboxsum += parseFloat(amount);
}
});
//addup the two totals
var totalAmount = textboxsum + addonsum;
//.toFixed() method will roundoff the final sum to 2 decimal
$(".total_amount").html(totalAmount.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>Total : <span class="total_amount"></span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">

Manipulating label with checkboxes

Scenario:
Three unchecked check-boxes, each with different id and value.
An empty paragraph (or label) with id = par.
[CB1] has value 1.
[CB2] has value 2.
[CB3] has value 3.
Now, when I click cb1 -> 'par' gets and prints the value of cb1.
Clicking on cb3, 'par' gets the value of cb1+cb3.
Clicking cb1, 'par' subtracts the value of cb1 and so on.. I think you get the point.
How can I achieve this with only HTML and JavaScript (without jQuery).
<input type="checkbox" id="1" value="1" />
<input type="checkbox" id="2" value="2" />
<input type="checkbox" id="3" value="3" />
<p id="par"></p>
This will do it: jsfiddle example (updated to remove alert)
HTML:
<input type="checkbox" id="1" value="1" onclick='checkClicked(event)'/>
<input type="checkbox" id="2" value="2" onclick='checkClicked(event)'/>
<input type="checkbox" id="3" value="3" onclick='checkClicked(event)'/>
<p id="par"></p>
JavaScript:
function checkClicked(element)
{
var targetElement = element.target;
var newVal = targetElement.value;
if( !targetElement.checked )
{
newVal *= -1;
}
var currentVal = document.getElementById('par').innerHTML;
if( currentVal )
{
newVal = parseInt(currentVal) + parseInt(newVal);
}
document.getElementById('par').innerHTML = newVal;
}
<label>
<input type="checkbox" id="check1" value="check1" onchange="alterP(this);"/>check1
</label>
<label>
<input type="checkbox" id="check2" value="check2" onchange="alterP(this);"/>check2
</label>
<label>
<input type="checkbox" id="check3" value="check3" onchange="alterP(this);"/>check3
</label>
<p id="par"></p>
js Code
function alterP(obj) {
var par = document.getElementById('par');
var txt = (obj.checked) ? obj.value : "";
par.innerHTML = txt;
}
<script>
document.getElementById("1").addEventListener("click", processCheck);
document.getElementById("2").addEventListener("click", processCheck);
document.getElementById("3").addEventListener("click", processCheck);
function processCheck() {
var theParagraph = document.getElementById("par");
var currentValue = 0;
if (!isNaN(parseInt(theParagraph.textContent))) {
currentValue = parseInt(theParagraph.textContent)
}
if (this.checked) {
theParagraph.textContent = currentValue + parseInt(this.value);
}
else {
theParagraph.textContent = currentValue - parseInt(this.value);
}
}
</script>

Limit checkbox based on value JavaScript

I'm trying to create a checkbox limit based on a value change example:
I have the following checkbox
<input type="checkbox" name="checkbox2[]" onClick="setChecks(this)" value="`key`=<?php
echo $rspatient['key']?>" class="chk" id="chk<?php echo $a++?>" />
I have a lot of check box as this is in a loop. Some have the same value others do not. Anyways wanting to create code that prevents checking boxes with different values!
Current code for limiting checkbox number:
<script>
<!--
//initial checkCount of zero
var checkCount = 0
//maximum number of allowed checked boxes
var maxChecks = 3
var d = document.getElementById('chk' + (j++));
function setChecks(obj) {
//increment/decrement checkCount
if (obj.checked) {
checkCount = checkCount + 1
} else {
checkCount = checkCount - 1
}
//if they checked a 4th box, uncheck the box, then decrement checkcount and pop alert
if (checkCount > maxChecks) {
obj.checked = false
checkCount = checkCount - 1
alert('you may only choose up to ' + maxChecks + ' options')
}
}
// -->
</script>
I tried to edit the final if statement with no luck!
After some messing around i managed to end up with this a working solution!
1 <input type="checkbox" value="1" /><br/>
2 <input type="checkbox" value="2" /><br/>
3 <input type="checkbox" value="3" /><br/>
1 <input type="checkbox" value="1" /><br/>
2 <input type="checkbox" value="2" /><br/>
3 <input type="checkbox" value="3" /><br/>
1 <input type="checkbox" value="1" /><br/>
2 <input type="checkbox" value="2" /><br/>
3 <input type="checkbox" value="3" /><br/>
$(function() {
var lastChecked = [];
$(':checkbox').change(function() {
if (this.checked) {
if (lastChecked.length && this.value != lastChecked[0].value) {
this.checked = false;
alert("the last box you checked has a different value");
}
else
{
lastChecked.unshift(this);
}
}
else {
lastChecked.splice(lastChecked.indexOf(this), 1);
}
});
});​
​
lastChecked.splice(lastChecked.indexOf(this), 1);
}
});
});​

javascript function for checkbox checked event

I need a function that can add checkbox values on click event. My html code is
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<center><b> Plattforms </b></center>
<input type="checkbox" name="cbs" id="cbs" value = 945345 />
<label for="cbs">945345 Symbian</label>
<input type="checkbox" name="cbi" id="cbi" value = 945345 />
<label for="cbi">945345 iPhone</label>
<input type="checkbox" name="cbb" id="cbb" value = 945345 />
<label for="cbb">945345 Blackberry</label>
<input type="checkbox" name="cba" id="cba" value = 945345 />
<label for="cba">945345 Android</label>
<input type="checkbox" name="cbw" id="cbw" value = 945345 />
<label for="cbw">945345 Windows Mobile</label>
<input type="checkbox" name="cbo" id="cbo" value = 945345 />
<label for="cbo">945345 All Other</label>
</fieldset>
</div>
The logic is when a user click on a checkbox, the checkbox value goes to a variable and again the user if clicks on another checkbox that value adds up into first value. Thanks in advance
Do you mean like:
var total = 0;
$("input[type='checkbox']").click(function() {
//if you want to add on checked
if($(this).is(":checked")) {
var v = parseInt($(this).val(), 10);
total += v;
}
else {
total -= v;
}
});
Hope it helps
You could do;
var tot = 0;
$("input:checkbox").click(function() {
var val = parseInt(this.value, 10);
if($(this).is(":checked")) {
//add to total if it's checked
tot += vale;
}else{
//this was previously checked, subtract it's value from total
tot -= vale;
}
});

How to compare field values with the same data attribute in javascript

How do I compare the values in the text fields with the same data attribute in javascript?
<input type="text" name="a" id="a" data-common="candy" class="loop" value="2">
<input type="text" name="b" id="b" data-common="candy" class="loop" value="3">
<input type="text" name="c" id="c" data-common="ice" class="loop" value="7">
<input type="text" name="d" id="d" data-common="ice" class="loop" value="2">
<input type="text" name="e" id="e" data-common="water" class="loop" value="5">
<input type="text" name="f" id="f" data-common="water" class="loop" value="9">
What I want to do is to determine the higher value on each of the fields with common data attribute. If the common attribute is candy, then the program will compare the values 2 and 3.
My problem is I can't think up of a good algorithm to even start coding. Can you give me an idea? What do I need to do first.
Here you go. The below code will find all the unique data-common attributes with max value.
Working demo
var dataAttributes = {}, attrValue, inputValue, $this;
$('input[data-common]').each(function() {
$this = $(this);
attrValue = $this.attr("data-common");
inputValue = parseInt($this.val());
if(!dataAttributes[attrValue]){
dataAttributes[attrValue] = inputValue;
}
else{
if(dataAttributes[attrValue] < inputValue){
dataAttributes[attrValue] = inputValue;
}
}
});
console.log(dataAttributes);
var datum = "candy";
var maxd = Number.NEGATIVE_INFINITY;;
$('input[data-common="'+datum+'"]').each(function() {
maxd = Math.max(maxd,$(this).val());
});
http://jsfiddle.net/KaUEX/
Well they already answered it, but I did the work so I'm going to post it
var common_values = {},
result = $('#result');
$('[data-common]').each(function(){
var element = $(this),
common_key = element.attr('data-common'),
value = parseInt(element.val(), 10);
if(typeof(common_values[common_key]) === 'undefined'){
common_values[common_key] = [];
}
common_values[common_key].push(value);
});
for(var data in common_values){//or you could find the min, or average or whatever
result.append(data + ': ' + Math.max.apply(Math, common_values[data]) + '<br>');
}
http://jsfiddle.net/dtanders/QKhu7/

Categories

Resources