stahlstngel stahlstngel - 4 months ago 17
HTML Question

HTML: live calculation via javascript (jquery) including variables with initialization

i am very new to JS and strugle with the following problem:

I want wo convert the value in the numberbox in the answer beside by any change of the value. Including the variables NP0, NP1 and DP0 from the HTML element.

-------------------------UPDATE 1--------------------------

To use html variables in javascript we can do this via data-* attributes. Thanks to Luca.

But how can I intitiate a calculation, when the page is loading for the first time?

And how can the calculation be executed on any change of the value?



$(".slide").on('change mousemove', function() {
$(this).next(".text").text(this.value)
});
$(".calc").on('change paste keyup', function() {
$(this).next(".text").text((128+(this.value*0.0625))/1)
});

<script src="http://code.jquery.com/jquery-2.2.2.min.js"></script>

<input name="period" class="slide" value="0.25" min="0" max="0.5" step="0.01" style="width: 15em;" type="range"><label class="text">0.25</label>

<br>
<br>
<input name="period" class="calc" value="0" min="0" max="4096" type="number" NP0="128" NP1="0.00625" DP0="1">= <label class="text"></label> km/h




Answer

You need data-* attributes, so your HTML should be

<input name="period" class="slide" value="0.25" min="0" max="0.5" step="0.01" style="width: 15em;" type="range"><label class="text">0.25</label>
<br>
<br>
<input name="period" class="calc" value="0" min="0" max="4096" type="number" data-NP0="128" data-NP1="0.00625" data-DP0="1">= <label class="text"></label> km/h

and your script

 $(".slide").on('change mousemove', function() { 
      $(this).next(".text").text(this.value)
 });
$(".calc").on('change paste keyup', function() {  
  $(this).next(".text").text(($(this).data("np0")+(this.value*$(this).data("np1")))/$(this).data("dp0"))
});

UPDATE 1

To compute your value immediately when you subscribe needed events, you can use trigger to force a "change" event, so your script should be

  $('.calc').on('change paste keyup', function(){
    $(this).next(".text").text(($(this).data("np0")+(this.value*$(this).data("np1")))/$(this).data("dp0"));
  }).trigger('change');

Sorry I miss a point :) To get continuous compute while spinning with buttons, you can add the "input" event, so your code become

  $('.calc').on('change paste keyup input', function(){
    $(this).next(".text").text(($(this).data("np0")+(this.value*$(this).data("np1")))/$(this).data("dp0"));
  }).trigger('change');

I updated the fiddle, again

Here a jsfiddle