Reputation: 367
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.
Upvotes: 1
Views: 141
Reputation: 2065
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.
Upvotes: 0
Reputation: 7373
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.
Upvotes: 1
Reputation: 17171
The main pieces of the problem are:
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.
Upvotes: 0