Get values from inputs, calculate them and show the result - javascript

I have these two text inputs:
<input type="text" value="" id="width" name="width" />
<input type="text" value="" id="height" name="height" />
And below there is:
<h1>Summ: xxxxxx</h1>
I want to replace xxxxx with the following math:
(width * height) / 2
Whenever I type a new value at width or height inputs, the Summ should change realtime.
Is this possible at all?
Thank you.

You have multiple options to do that. There are many technologies frameworks, libraries, and ways to do it.
In my case (as I'm more familiar with this), the easier would be to use JQuery like this.
$('#width, #height').on('input', function(){
var width = $('#width').val();
var height = $('#height').val();
if (width != "" && height != "")
$('#result').text(width*height/2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="" id="width" name="width" />
<input type="number" value="" id="height" name="height" />
<h1>Result: <span id='result'>0</span></h1>
Obs: I changed your input fields to numeric type, so the user won't enter non-numeric data.

Quick fix:
<input type="text" value="" id="width" name="width" />
<input type="text" value="" id="height" name="height" />
<h1 class="calc"></h1>
And:
$('#width, #height').on('input', function () {
var widthInput = $('#width').val()
var heightInput = $('#height').val()
var result = widthInput * heightInput / 2
$('.calc').text(result)
})
You might wanna put a placeholder value like 1 for each field so it doesn't begin calculating with a 0. Also, it's spelled "sum" and not "summ", and it's not a sum anyway.
Fiddle here.

The main pieces of the problem are:
How do I get the value of an input box?
How do I execute code whenever input changes?
How do I set the text of an element?
The relevant functions are val(), change(), and text() respectively. The examples in the documentation should help you figure out how to piece it all together.

Related

html output tag doesn't display output

I have initial values displaying in the fields and want the initial total of the calculated value to display.
The total only displays once a field is modified. I am guessing because it reacts to oninput event.
Code:
<form id="form" oninput="result.value = parseInt(field1.value) + parseInt(field2.value)">
<input type="number" name="field1" id="field1" value="600">
<input type="number" name="field2" id="field2" value="200">
Total <output name="result" id="result" value="document.write(this.result.value)">
</output>
</form>
I could type 800 inside the output tag, but I want it to be dynamic.
Your document.write isn't doing anything useful (it's basically saying "set this attribute to the value of this attribute") and can be removed; rather than writing the value into the HTML you can just set the form field's value attribute in js.
Here I've simplified your code by removing the nonessential or nonfunctional parts, moving the javascript out of the HTML attributes, and combining the "initialize" and "update" tasks into a single function:
// these happen implicitly based on the field IDs; I'm redeclaring
// them here just for clarity, but you could leave these next four
// lines out and this code would still work:
var result = document.getElementById('result')
var field1 = document.getElementById('field1');
var field2 = document.getElementById('field2');
var form = document.getElementById('form');
// update value on input:
form.oninput = function() {
// use Number() instead of parseInt() if you want to support non-integer values here
result.value = parseInt(field1.value) + parseInt(field2.value);
}
// set initial value on page load by calling that function:
form.oninput()
<form id="form">
<input type="number" id="field1" value="600">
<input type="number" id="field2" value="200">
Total <output id="result"></output>
</form>
You can use document.getElementById() and specify the id of the input fields.
Because the value for the input fields is a string, you need to convert to those values to type Number by the Number() function.
let value1 = Number(document.getElementById('field1').value);
let value2 = Number(document.getElementById('field2').value);
result.value = value1 + value2;
<form id="form" oninput="result.value=parseInt(field1.value)+parseInt(field2.value)">
<input type="number" name="field1" id="field1" value="600">
<input type="number" name="field2" id="field2" value="200">
Total <output name="result" id="result" value="document.write(this.result.value)"></output>
</form>
You can read more info about document.getElementById() and Number()

Finding the value of multiple input boxes

I'm building a multiple quantity selector for my store. Image below:
On the site, the price of the product updates based on the quantity added. 10 products = 10% off etc. I'd like to be able to display this price change as and when the user edits any one of the input boxes in the quantity selector.
The input fields are built like this:
<div data-value="S" data-varientid="8195426353207" class="swatch-element swatch-element-2 size s available">
<input id="swatch-0-s" data-variant-id="variant_8195426353207" type="checkbox" name="option-0" value="S">
<label for="swatch-0-s">
S
<img class="crossed-out" src="//cdn.shopify.com/s/files/1/0020/2188/3959/t/2/assets/soldout.png?5180939831627851747" alt="">
</label>
<input id="qty" name="quantity" class="swatchinput" placeholder="0" value="0" type="text">
</div>
I'm able to watch the input boxes for change by doing the below:
var qty = $('.swatchinput');
$('.swatchinput').on('paste keyup', function() {
console.log(qty);
});
However, this returns the information about the element rather than the contents. I'm also unsure of the best way to then add the contents of the various input fields together to reach the total quantity.
You could also use the Array reduce method to do this. Select all the inputs, get the array, then reduce their values into the sum.
var total = $('.swatchinput').get().reduce(function(total, input){
return total + parseInt(input.value || '0');
}, 0);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="quantity" class="swatchinput" placeholder="0" value="1" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="2" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="3" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="4" type="text">
This needs to be
var qty = $('.swatchinput').val();
not
var qty = $('.swatchinput');
As for your second question,
loop each of these inputs, getting the value, then add them up with a total. Initialize the total OUTSIDE of the loop also so it doesn't overwrite it.
Something like this?
var total = 0;
$('.switchinput').each(function(){
total += $(this).val();
});
console.log(total);
To get the value of an element in jQuery, use .val():
http://api.jquery.com/val/
.each loops through each matched element and runs a function on that element (accessible through 'this')
http://api.jquery.com/each/

Add (or multiply, subtract or divide) one var to another in JS/jQuery

Sincere apologies if this has been asked and answered elsewhere, I struggled with finding accurate search terms for this.
Working in jQuery I have a var called total. I need to add the value of other vars to total. All the vars in question have numerical values.
This is what I've tried:
var total = total+rocketspend;
$(".totalamount").html(total);
and
var newtotal = total+rocketspend;
var total = newtotal;
$(".totalamount").html(total);
Both have resulted in .totalamount being emptied and replaced with nothing. I have theories around why this might be going wrong - it could be that in the first example a var isn't allowed to be self defining, and it could be that in in the second example the browser attempts to define both newtotal and total at the same time, ending in mystery. Or it could be something else entirely. The rocketspend var works fine on its own, as does total before the attempted addition.
Thoughts?
You only need to use var when you first define a variable. It looks like you're trying to access a variable that already exists. Example:
var total = 0;
var rocketspend = 10;
total = total + rocketspend;
$(".totalamount").html(total);
Additionally, try checking your console for any errors. In most browsers, you can right click and inspect an element or click Ctrl + Shift + I and clicking on the Console tab. You can use Ctrl + Shift + K in Firefox.
You are using jQuery and have referenced an element (i.e. .totalamount) so assuming you are using normal webpage (i.e. HTML, CSS, JS/jQ etc..), this Snippet has 2 <forms>. The first one uses only JavaScript and HTML5. The second form uses jQuery and HTML5.
When using form fields such as <input>, the value you type in them will be a string (i.e. text) value. So when "3" is typed in, the <input> will treat it as text not a real number value. So convert the string to a number, use parseFloat(), parseInt(), or Number().
To get <input> values use .val() (jQuery) or .value (JavaScript).
SNIPPET
$('#calc1').on('input', function() {
var rocket1 = $('#rocket1').val();
var sub1 = $('#sub1').val();
var total1 = parseFloat(sub1) + parseFloat(rocket1);
$("#total1").val(total1);
});
input {width: 8ex;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Using only plain JavaScript and HTML5 form fields</p>
<form id="calc" name="calc" oninput="total.value = parseFloat(sub.value, 10) + parseFloat(rocket.value, 10)">
<fieldset>
<legend>Rocket Expenditure</legend>
<label for="sub">
<b>Sub Total:</b>
<input type="number" id="sub" name="sub" value="0">
</label> +
<label for="rocket">
<b>Rocket:</b>
<input type="number" id="rocket" name="rocket" value="0">
</label>
<label>
<b>Total:</b>
<output name="total" for="sub rocket">0</output>
</label>
</fieldset>
</form>
<p>Using jQuery and HTML5 form fields</p>
<form id="calc1" name="calc1">
<fieldset>
<legend>Rocket Expenditure 1</legend>
<label for="sub1">
<b>Sub Total 1:</b>
<input type="number" id="sub1" name="sub1" value="0">
</label> +
<label for="rocket1">
<b>Rocket 1:</b>
<input type="number" id="rocket1" name="rocket1" value="0">
</label>
<label>
<b>Total 1:</b>
<output id="total1" name="total1" for="sub1 rocket1">0</output>
</label>
</fieldset>
</form>

Multiplying calculator

I am trying to create a simple calculator that takes a number from 1 text box and after hitting a submit button it takes the number and multiplies it by 92 then puts it in a read only box.
This is what I have so far:
<form name="1star">
<input type="text" name="input"/>
<input type="button" value="Enter" OnClick="1star.output.value == 1star.input.value * 92"/>
<br/>
<input type="text" name="output" readonly="readonly" />
</form>
This is not working and I could use some help. I know its easy but I am very new to js and I'm not understanding why this isn't working.
<form name="onestar">
<input type="text" name="input"/>
<input type="button" value="Enter" OnClick="onestar.output.value = onestar.input.value * 92"/>
<br/>
<input type="text" name="output" readonly="readonly" />
</form>
An identifier cannot start with a digit in JavaScript, so 1star is an error. Also, you wanted = (assignment), not == (comparison).
That said, there are a number of outdated or beginner practices above. If I was writing it, I would separate the script from the markup, and I'd use document.getElementById to fetch the element rather than relying on implicit variables defined by name. I would also explicitly parse the string into a number. But for now no need to worry about it too much. Even though the code seems much more complicated at first glance, it's all things that will make your life easier later, with bigger programs.
var input = document.getElementById('input');
var output = document.getElementById('output');
var button = document.getElementById('button');
button.addEventListener('click', function(evt) {
var value = parseInt(input.value, 10);
if (!isNaN(value)) {
output.value = value * 92;
}
});
<form>
<input type="text" id="input"/>
<input type="button" id="button" value="Enter"/>
<br/>
<input type="text" id="output" readonly="readonly" />
</form>

Jquery constraint proportions with width and height input fields

I have a form with width and height input fields.
I want to listen to changes made in any one of the fields by the user
and change the value in the other field wile constraint proportions using Jquery.
the user can see the changes as he typs.
<form>
<p>
<label>Width</label><br />
<input type="text" id="width" value="16" />
</p>
<p>
<label>Height</label>
<input type="text" id="height" value="9" />
</p>
</form>
How about this. I am storing the original value in data-value attribute, that I use to recount the ratio
<form>
<p>
<label>Width</label><br />
<input type="text" id="width" data-value="16" value="16" />
</p>
<p>
<label>Height</label>
<input type="text" id="height" data-value="9" value="9" />
</p>
</form>​​​​​​​​​
Here is the listener for changing width (you can write the one for height in the same way)
​$("#width").bind("keyup", function(){
var width = $(this).data("value")
, newwidth = $(this).val()
, $height = $("#height")
, height = $height.val();
$height.val(height*(newwidth/width));
})​
Here is the fiddle
try attaching an event to .keypress( handler(eventObject) ) that for every keypress that the used does it performs what you said above.

Categories

Resources