dominotrix
dominotrix

Reputation: 367

Get values from inputs, calculate them and show the result

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

Answers (3)

Yeats
Yeats

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.

Fiddle here.

Upvotes: 0

Mauricio Moraes
Mauricio Moraes

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

Samuel
Samuel

Reputation: 17171

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.

Upvotes: 0

Related Questions