Search code examples
javascriptjqueryhtmlrefreshreload

How do you reload a variable shown in HTML when it changes value?


My HTML shows a variable inside of a script tag, and I want to reload only that variable.

<script class="scriptClass">document.write(myObject.myProperty);</script>
<button>Go</button>

When a function runs that changes the value of myObject.myProperty, it needs to be updated in the HTML. JavaScript is something like this:

var myObject = {
    myProperty:"Initial"
};
function myPropertyChange(){
    myObject.myProperty = "somethingDifferent";
}

jQuery:

$(document).ready(function() {
    $("button").click(function(){
        myPropertyChange();
        $("script.scriptClass").empty();
        $("script.scriptClass").html("document.write(myObject.myProperty);");
    });
});

This doesn't work, and I've tried a number a variations on this with .replaceWith and .replace. I also tried adding location.reload(true);, but I think that just resets the whole thing.


Solution

  • Instead of reloading a <script> tag, can you assign it to a <div>. Something like this:

    myObject = {};
    myObject.myProperty = "Initial";
    function myPropertyChange(){
      myObject.myProperty = "somethingDifferent";
      $("#theProperty").text(myObject.myProperty);
    }
    
    $(document).ready(function() {
      $("#theProperty").text(myObject.myProperty);
      $("button").click(function(){
        myPropertyChange();
        $("script.scriptClass").empty();
        $("script.scriptClass").html("document.write(myObject.myProperty);");
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <span id="theProperty"></span>
    <button>Go</button>