Javascript function adding checkboxes to a total number? - javascript

I have a function where I'm trying to add the total number of checkboxes ticked to a value that is already displayed in the textbox. The solution I have works but it doesn't update properly if I uncheck the boxes and click total again.
Is there a way I can fix this so that the textbox updates accordingly?
HTML
<td><input type="text" name="Yeses" id="NumberofRisks" class = "form-control" value ="<?php echo $row['Total-Score'];?> " style = "width:50px"></td>
Javascript
function sum()
{
sumField = document.getElementById("NumberofRisks");
var sum = sumField.value;
$("input[name^='yanswer']:checked").each(function(){
sum++;
});
sumField.value = sum;
}

You are updating the value of the input after every call to function sum().
Instead have the initial sum value.
Then every time use this value.
var initial = $("#NumberofRisks").val();
function sum()
{
$("#NumberofRisks").val(initial + $("input[name^='yanswer']:checked").length);
displayRating($("#NumberofRisks").val());
}

Keep the original value of the textbox in a variable. Add an event listener to the checkboxes that count the number of checked boxes and adds that number to the original value, then updates the textbox.
Something like this:
HTML:
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="textbox" class="text" />
JS:
//Store the original value. The 5 here should be whatever was supposed to be in the textbox.
var originalValue = 5;
$('.text').val(originalValue);
$('.check').on('change', function() {
//Count the number of checked boxes and add it to the original value for display.
var checked = $('.check:checked').length;
$('.text').val(originalValue+checked);
});
Here's a fiddle.

Related

It seems onChange="myFunction()" is only calling my function once?

I have the following HTML that is within a form, to accept 2 numbers from two separate inputs
<input type="number" id="amount" name="amount" value="0" onchange="ltv()">
<input type="number" id="property_value" name="property_value" value="0" onchange="ltv()">
<p id="ltv"></p>
Then some JavaScript
function ltv() {
var amount = document.getElementById("amount").textContent;
var property_value = document.getElementById("property_value").textContent;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
However after entering a number into the "amount" input the ltv element is updated with NaN which is to be expected at this stage as only the first variable in the math operation is set, however upon entering the second number and tabbing away from the input field the ltv is not updated again.
Seems like textContent isn't returning anything. Try to use .value
function ltv() {
var amount = document.getElementById("amount").value;
var property_value = document.getElementById("property_value").value;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};

How can i get attribute value from a checkbox if it's checked?

Well, I have this text input that gets sum of all the attributes of "price" inside all checkboxes are checked.
now i can't get an attribute value from a checkbox.
here is my function:
function sum_options() {
var options = [];
$("#form-field-1-11-1").attr("price", 500);
$("#form-field-1-11-2").attr("price", 500);
$("#form-field-1-11-3").attr("price", 0);
$("#form-field-1-11-4").attr("price", 300);
$("#form-field-1-11-5").attr("price", 500);
$("#form-field-1-11-6").attr("price", 500);
$("#form-field-1-11-7").attr("price", 1250);
$("#form-field-1-11-8").attr("price", 500);
$("#form-field-1-11-9").attr("price", 700);
options[0] = $("#form-field-1-11-1");
options[1] = $("#form-field-1-11-2");
options[2] = $("#form-field-1-11-3");
options[3] = $("#form-field-1-11-4");
options[4] = $("#form-field-1-11-5");
options[5] = $("#form-field-1-11-6");
options[6] = $("#form-field-1-11-7");
options[7] = $("#form-field-1-11-8");
options[8] = $("#form-field-1-11-9");
var total = 0;
$.each(options, function() {
this.on("change", function() {
total += this.attr("price");
});
});
$("#sum-field").val(total);
}
thanks!!!
Your code is a lot more complex than it needs to be.
Firstly, you should use data-* attributes to assign custom data to an element. Creating your own non-standard attributes will mean your HTML is invalid and can lead to other issues. Also, if your code is relying on the price attribute, then it should be in the DOM when the page loads.
Secondly there's no need to build an array of single elements. You can select them all in to a single jQuery object and set a change() event handler on them in a single call. I grouped them by class in the below example.
Lastly you can get the total of all the prices by looping through the :checked boxes and adding up their prices. Try this:
$('.checkbox').change(function() {
var total = 0;
$('.checkbox:checked').each(function() {
total += parseFloat($(this).data('price'));
});
$("#sum-field").val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="form-field-1-11-1" class="checkbox" data-price="500" />
<input type="checkbox" id="form-field-1-11-2" class="checkbox" data-price="500" />
<input type="checkbox" id="form-field-1-11-3" class="checkbox" data-price="0" />
<input type="checkbox" id="form-field-1-11-4" class="checkbox" data-price="300" />
<!-- other checkboxes here... -->
<input type="text" id="sum-field" />
To get the value of the Value attribute you can do something like this:
$("input[type='checkbox']").val();
Or if you have set a class or id for it, you can:
$('#check_id').val();
$('.check_class').val();
However this will return the same value whether it is checked or not, this can be confusing as it is differnt to the submitted form behaviour.
To check whether it is checked or not, do:
if ($('#check_id').is(":checked"))
{
// it is checked
}
You just forgot to parse the return value to a number:
parseInt(this.attr("price"));
the attr() function is returning a string value.

How to add sum in my input value and chage

I have this code:
<input id=​"InvoiceItemPrice:​:​:​:​" name=​"InvoiceItemPrice:​:​:​:​" value size=​"6">​
<input id=​"InvoiceItemPrice:​:​1:​:​" name=​"InvoiceItemPrice:​:​1:​:​" value=​"46.00" size=​"6">​
<input id=​"InvoiceItemPrice:​:​2:​:​" name=​"InvoiceItemPrice:​:​2:​:​" value=​"79.00" size=​"6">​,
<input id=​"InvoiceItemPrice:​:​3:​:​" name=​"InvoiceItemPrice:​:​3:​:​" value=​"14.00" size=​"6">​
I like add sum in every value ot input type i have this code:
var sum = 100/123;
$('input[name="InvoiceItemPrice::2::"]').each(function()
{
sum *= parseFloat($(this).val());
});
$('input[name="InvoiceItemPrice::2::"]').val(sum);
How to change all value on all input.
I tried with this $("input [name = ' * InvoiceItemPrice ']") but I caught the first that does not have a value and NaN gives me an error.
What is happening is your sum variable is getting re-used in your each statement, if you change that line inside of your each you should be A-ok.
I have created a jsFiddle here https://jsfiddle.net/r79d3121/3/ which may help
HTML
<input id="InvoiceItemPrice::::" name="InvoiceItemPrice::::" value size="6">
<input id="InvoiceItemPrice::1::" name="InvoiceItemPrice::1::" value="46.00" size="6">
<input id="InvoiceItemPrice::2::" name="InvoiceItemPrice::2::" value="79.00" size="6">,
<input id="InvoiceItemPrice::3::" name="InvoiceItemPrice::3::" value="14.00" size="6">
jQuery
var sum = parseFloat(100 / 123);
$(function () {
var result = 0;
$('[id*="InvoiceItemPrice"]').each(function () {
$(this).val(parseFloat((parseFloat($(this).val()) * parseFloat(sum))));
});
});
Updated to change only the value from the input selected
2nd Update, values are calculated when the document is ready, if you want the values to be updated you could always check for .focusout() on each input and then run the code to calculate the value
3rd Update, the html is back to the original and also, you can just user a partial selector in your jQuery which I have provided and updated the jsFiddle link
Try something like this:
$('input[name^=InvoiceItemPrice]').each(function() {
$(this).val("example");
});

How to change Uptick Increments in HTML Number Input

I have a number input form:
<input type='number' id='select-number'>Pick A number
I have the following questions:
1: The default uptick increment is 1 (when you click the up arrow on the number input, it goes up by a value of one per click.) How can I change that? I want it to go up in values of 0.1 (tenths). How do I do that?
2: Secondly, I have two variables:
feet=true;
meters=false;
One will always be true, and the other false. How do I change the "max" attribute (using Javascript) based on which of these two variables is true? The two variables come from code something like this:
<input type='radio' id='feet' name='unit_of_measurement'>Feet
<input type='radio' id='meters' name='unit_of_measurement'>Meters
<script>
feet=document.getElementById('feet').checked;
meters=document.getElementById('meters').checked;
</script>
If the variable "feet" is true, then the maximum value of the input (Id='select-number') needs to be 3. If it is meters, it needs to be 8.
How can I do that(^), and how can I change the uptick increment? Thanks for any help.
NOTE: Vanilla Javascript only, Please
1) To change the step of an input simply use step=".1" inside the input tag.
2) To change the max on radio change add a onchange="change()" which sets the max and/or step based on which is checked
html
<input type='radio' id='feet' name='unit_of_measurement' onchange="change()" checked>Feet
<input type='radio' id='meters' name='unit_of_measurement' onchange="change()">Meters
js
function change() {
feet = document.getElementById('feet').checked;
meters = document.getElementById('meters').checked;
selectNumber = document.getElementById('select-number');
if (feet) {
selectNumber.max = 300;
selectNumber.step = 1;
} else {
selectNumber.max = 100;
selectNumber.step = .3;
}
};
fiddle or fiddle 2
The default uptick increment can be modified by using step attribute
<input type="number" name="quantity" step="0.1">
and any property can be accessed (set and get) by getting handle of DOM element.
oldValue = document.getElementById('#<id>').propertyName; //get
document.getElementById('#<id>').propertyName = newValue; //set

jQuery - Count number of checked checkboxes with a given Id value

I have a page with a table on it. Two of the columns in the table are checkbox columns. Each has a different Id value. I'm trying to count, via jQuery, the number of rows in the table where one of the checkbox columns (which has an Id value of 'InChecklist') is checked. My JS function looks as follows:
function UpdateCount() {
var totalRows = $('#checklistTable tbody tr:visible').length;
var totalSeen = $(":input#InChecklist[checked='checked']").length;
$("#rowCount").text(totalRows.toString() + " species / " + totalSeen + " seen")
}
The total row count is fine. But I must not have the syntax correct for the total seen because I cannot get it to count correctly (the value is always zero). If I remove the '#InChecklist', I do get a value greater than zero, but in this case, it's counting the total checked in both checkbox columns, not the one with an Id of 'InChecklist'.
If it helps, the portion of my HTML that renders the checkboxes look as follows. It's MVC5.
<td>
<input id="InChecklist" name="item.HasBeenSeenChecklist" type="checkbox" value="true" /><input name="item.HasBeenSeenChecklist" type="hidden" value="false" />
</td>
<td>
<input id="InLifelist" name="item.HasBeenSeenLifelist" type="checkbox" value="true" /><input name="item.HasBeenSeenLifelist" type="hidden" value="false" />
</td>
Specify the ID before the :input like this
var totalSeen = $("#InChecklist:input[checked='checked']").length;
Edit
var totalSeen = $("input#InChecklist:checked").length;
EDITED:
you can try:
var totalSeen = $("#InChecklist input:checked").length;
selects all the children inputs of #InChecklist
alternatively you can use this:
var totalSeen=0;
$("#InChecklist input").each(function(){
if($(this).is('checked')){
totalSeen++;
}
});

Categories