How to take sum of an empty div with an id? - javascript

Write a function named "additionCalculator" that that doesn't take any parameters and doesn't return a value. This function will control the logic for a web-based calculator that adds two numbers. There will be two text boxes on the web page with ids of "input_one" and "input_two" and an empty div with an id of "sum". Read the values of the two text boxes and write the addition of these two values inside the div.
function additionCalculator(){
var one = parseInt(document.getElementById('input_one'));
var two = parseInt(document.getElementById('input_two'));
var sum = one + two;
document.getElementById('sum').value = sum;
}
I can't seem to add the two numbers together. What am I doing wrong?

document.getElementById returns an HTML element - you want the value of the element (I assume these are inputs) - so you need to get the actual property:
var one = parseInt(document.getElementById('input_one').value);
var two = parseInt(document.getElementById('input_two').value);
When setting the value back to the div - use the innerHTML property:
document.getElementById('sum').innerHTML = sum;

Try this, I think what you're missing is a button that calls the action for the calculation to happen. Also remember to change your statements to get the value of the inputs and to target the innerHTML of the empty div
document.getElementById('sumBtn').onclick = function additionCalculator(){
var one = parseInt(document.getElementById('input_one').value);
var two = parseInt(document.getElementById('input_two').value);
var sum = one + two;
document.getElementById('sum').innerHTML = sum;
}
<input type="text" id="input_one">
<input type="text" id="input_two">
<button id="sumBtn">Add</button>
<div id="sum"></div>

Related

Is there any way to add value of two <h> tags using jquery?

I have two <h4> tags, one which contain price, and another contains percentage value. I need to find the percentage and set into new <h4> tag.
I tried to calculate but which return NaN instead. I tried alert(parseFloat(price)+parseFloat(percent)) which return concatenated result, not the sum(for just testing).
I tried following, value is assigned based on checkbox click.
$("#checkbox1").click(function () {
if ($(this).prop("checked")) {
var price = $("#tex2").text();
var percent = $("#percent").text();
price = parseFloat(price);
percent= parseFloat(percent);
var dis_price;
dis_price = parseFloat(dis_price);
dis_price = price-(percent/100)*price;
$('#tex1').text(dis_price);
}
else {
$("#tex1").text("test");
}
});
I want to get calculated value instead of NaN. Please find me way to solve this problem.
without jquery it will be simpler (the + make implicit cast string to number)
var price = +tex2.innerText;
var per = +percent.innerText;
tex1.innerText = price-(per/100)*price;
function make(check) {
if(check.checked) {
var price = +tex2.innerText;
var per = +percent.innerText;
tex1.innerText = price-(per/100)*price;
} else {
tex1.innerText = 'test';
}
}
<input type="checkbox" onchange="make(this)">Click</button>
<div>
<h id="tex2">10</h>
<h id="percent">20</h>
<h id="tex1"></h>
</div>
A math operation on an undefined value will return NaN. Make sure your referenced values are not undefined.

Gravity Forms use JS to count rows in List and return to field?

I am trying to make a sign up form in gravity forms that uses the list field so multiple people can be signed up at once. The problem is I also need to get a quantity of how many people are signing up so I can charge a fee for each.
With JS, how would I count the number of rows in the list and pass the value to another field? Or is there a better method to do this?
UPDATE:
Based on Obsidian Age's answer, this refreshes occasionally and outputs to the quantity field:
function updateQty() {
var rows = document.querySelectorAll('.gfield_list_group').length; // Count rows
var qty = document.querySelector('.ginput_quantity'); // Define output location
qty.value = rows; // Put row count in location
setTimeout(updateQty, 2000); // Repeat every 2 seconds
}
updateQty(); // Execute
I'm not familiar with the particular plugin's outputted markup, but you can simply grab all of the desired elements with something like .querySelectorAll(). From here, it's trivial to find the number of them by simply querying their .length. If you assign this number to a variable, you can reference it later on when you want to insert it back to a different field -- which can be done by updating the element's .innerHTML with the variable.
This can be seen in the following:
const amount = document.querySelectorAll('.row').length;
const output = document.querySelector('.output');
output.innerHTML = amount;
<div class="row">One</div>
<div class="row">Two</div>
<div class="row">Three</div>
<div class="row">Four</div>
<br />
<div class="output"></div>
<script>
jQuery.expr[':'].hasValue = function(el, index, match) {
return el.value != "";
};
function updateQty() {
var listFieldID = '#field_85_12 .gfield_list_12_cell1 input:hasValue';
var totalFieldID = '#input_85_35';
var totalRows = $(listFieldID).length; // Count rows
var totalField = $(totalFieldID);
console.log(totalRows); // For testing
$( totalField ).val( totalRows +1 ).change();
setTimeout(updateQty, 3000); // Repeat every 2 seconds
}
updateQty(); // Execute
</script>

Use Selected Options Value in For Loop

Good afternoon.
I am trying to use the selected value in the options box in a for loop.
The theory being that if the user selects 3, for example, Javascript will populate 3 boxes with a fruit from the array.
Can anyone point me in the right direction? I have enclosed Codepen link too.
function changeText(){
var e = document.getElementById('selectbox');
var strUser = e.options[e.selectedIndex].value;
for (var i=0; i<=strUser; i++) {
document.getElementById('boldStuff').innerHTML = randomFruit + strUser;
}
}
http://codepen.io/jameswinfield/pen/aNWRKm
The ID element should be unique to the entire dom. You are using it multiple times for boldStuff. If you would like to be able to grab them like that you should use a class.
Here is a version that should do what you want: http://codepen.io/anon/pen/KzmGLP?editors=0010
Keep in mind that sets the value to every box, even the hidden ones. You will have to get a new random fruit per box or they will all have the same fruit.
I changed all id="boldStuff" to class="boldStuff",
grabbed all boldStuffs
var boldStuffs = document.getElementsByClassName('boldStuff');
and looped over every boldStuff
for (var i = 0; i < boldStuffs.length; i += 1) {
//And set the value of each boldStuff to a new random fruit.
boldStuffs[i].innerHTML = getRandomItem(fruitsArray);
}
The following line also only runs once so no matter how many boxes there are they will all have the same fruit (because randomFruit is never changed)
var randomFruit = fruitsArray[Math.floor(Math.random() * fruitsArray.length)];
You can use a function to grab a random fruit instead, something like this:
function getRandomItem(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
Then use getRandomItem(fruitsArray); to get a random fruit.

Javascript - For each Name set ID equal to Name[i] AND validate

Okay I've created an invoice where depending on the number of invoiced items, it will generate a check box next to each one for approval. Each checkbox will have the name invoiceApproval.
So far my script will count to see how many inputs have the name invoiceApproval then assign an ID to each one with the ID = invoiceApproval[i]
That is working perfectly, but now when I use the JavaScript Form Validation : quick and easy! in HTML Forms to assign a frmvalidator.addValidation for each ID (the number of each being equal to how many checkboxes have the name invoiceApproval) it only validates the first box with the ID invoiceApproval0.
Why will my 'for each' only work for the first instance??? What am I doing wrong here:
<script type="text/javascript">
var frmvalidator = new Validator("forminvoice");
var inva = document.getElementsByName("invoiceApproval");
for (var i = 0; i < inva.length;i++) {
var inc = "invoiceApproval"+[i];
inva[i].setAttribute("id",inc);
}
var inva = document.getElementsByName("invoiceApproval");
for (var i = 0; i < inva.length;i++) {
var inc = "invoiceApproval"+[i];
frmvalidator.addValidation(inc,"shouldselchk=x","You must check off each item on the right hand side of the invoice before you can submit approval.");
}
</script>
And the PHP loop that generates the checkboxes is:
while($row = mysql_fetch_array($result))
{
echo "<input type='checkbox' value='x' name ='invoiceApproval' > Approve";
}
The library's code is using
var itemobj = this.formobj[itemname];
to retrieve the form item. Later it does
if (itemobj.length && isNaN(itemobj.selectedIndex))
{
itemobj = itemobj[0];
}
Which means that if there are multiple items with the same name, it will always choose the first one. Taking names for references to your form fields is such bad practice
The only solution (if you want to work with this library, but I would stay away from it, it's really poorly written) is to make your names not be the same.
Side Note
The line
var inc = "invoiceApproval"+[i];
Is creating an array with a single value in it, and then toString is being called on it, and toString (luckily for you) returns a single value array as the value itself. Get rid of those brackets, it should be
var inc = "invoiceApproval"+i;

Form value addition with js

I'm trying to write a order form that shows the value of the selected items automatically. The backend is already complete, and on the front end each field, all radio / checkbox, look like this:
<input type="radio" name="shirt-size" value="shirt_size_m[18]" />
'18' being the price, everything else being irrelevant to the front end price calculation. I cannot change the naming convention, so I need to get the value between the brackets on all the <input>s on the page (or below the parent ID), add them together (on update), and append the value to another ID. Jquery is already in use on the site if that makes thongs easier.
I just need to be pointed in the right direction as my JS experience is limited to examples and minor customizations :)
Try using a simple regular expression with Javascript's replace, to replace all non-numeric characters with the empty string:
var str = "shirt_size_m[18]";
var theNumber = parseInt(str.replace(/[^0-9]/g, ''));
alert(theNumber);
Demo: http://jsfiddle.net/XvTaY/1/
You could try something like this:
function calculate_sum(form_id) {
var $form = $(form_id);
var sum = 0;
$checkbox_and_radios = $form.find('input[type=checkbox], input[type=radio]').each(function(){
sum += parseInt($(this).val().match(/^[^\[]+\[(\d+)\]$/)[1]);
});
return sum;
}
$(function(){
$("#id_of_the_form").find('input[type=checkbox], input[type=radio]').change(function(){
var sum = calculate_sum("#form_id");
// I don't know the type of your element containing
// the sum, so I put multiple solutions here:
// some input element
$('#another_id').val(sum);
// or another element
$('#another_id').html(sum);
// I'm assuming you don't really mean append
// If you're sure you want to append: (but then the old value won't be deleted)
$('#another_id').append(sum);
});
});
u can use:
var v;
v = $('#input-identifier').val();
v = v.split("[");
v = v[1];
v = v.split("]");
v = v[0];
// now v has the number

Categories