Zach Brantmeier
Zach Brantmeier

Reputation: 746

Updating values in Javascript/HTML

I have this tag in my HTML:

<p id="moneyvalue"></p>

And I have this Javascript code:

var moneyBalance = 0;
document.getElementById('moneyvalue').innerHTML=moneyBalance;

I have onclick=..., which causes functions to add to the moneyBalance variable. The problem is that the paragraph element with the moneyvalue id does not update until I call the last line of code I mentioned. Is there a way to constantly update the element without needing to call that line after every update I make to the moneyBalance variable, or is that the only way to do that?

Upvotes: 0

Views: 2669

Answers (4)

user2816674
user2816674

Reputation:

You could make that code run every time your moneyBalance value is changed by putting them both into a function like so:

function change_balance(new_value) {
    moneyBalance = new_value;
    document.getElementById('moneyvalue').innerHTML = moneyBalance;
}

So now instead of calling moneyBalance = X, you call change_balance(X) and it will update at the same time.

Upvotes: 4

Milan and Friends
Milan and Friends

Reputation: 5610

I don't know how do you update moneyBalance variable but here's a jQuery exapmle of auto update values. FIDDLE

<div class="wrapper">
  <input type="text" id="val1"/> 
  <p id="moneyvalue"></p>
</div>

<!-- Or jQueryUI Slider version-->

<div class="wrapper">
  <input type="text" id="val2"/>
  <div id="slider"></div>
</div>


.wrapper {
  width: 310px;
  height: 20px;
  margin: 10px;
}
p,
#val2 {
  font-family: Verdana;
  font-size: 14px;
  font-weight: 600;
  letter-spacing: 1px;
  color: blue;    
}
#val1 {
  float: left;
  width: 207px;
  margin: 0 10px;
}
#val2 {
  float: right;
  width: 50px;
  margin: -4px 0;
}
p {
  display: block;
  float: right;
  width: 50px;
  height: 20px;
  margin: 0;
  padding: 0 2px;
  border: 1px solid #bbb;
}
#slider {
  width: 200px;
  margin: 50px 0 0 20px;
}

<script>
$(function() {

  $('#val1').keyup(function() {
    $('#moneyvalue').text('$'+$(this).val());
  }).change(function() {
     if(!$('#val1').val()) {
        $('#moneyvalue').text('$0');
     }
  });

  $('#moneyvalue').text('$0');


  // *** Or jQueryUI Slider version ***************


  $('#slider').slider({
     range: 'min',
     min: 0,
     max: 500,
     slide: function(event, sl) {
       $('#val2').val('$' + sl.value);
     }
  });

  $('#val2').val('$'+$('#slider').slider('value'));

});
</script>

Upvotes: 0

yayaya
yayaya

Reputation: 11

you can use setInterval()

So your code becomes

setInterval(function(){ document.getElementById('moneyvalue').innerHTML=moneyBalance; }, updateTime);

where updateTime in millisecs means when it will update.

Upvotes: 1

Carlo Cannas
Carlo Cannas

Reputation: 3262

No, it isn't possibile. However, I'd suggest to use textContent property instead of innerHTML, since it doesn't trigger the HTML parser.

Upvotes: 0

Related Questions