How to update/change HTML content with JavaScript and prevent the page from refreshing?

14,390

Solution 1

Don’t use a form at all. You are not submitting any form data to a server. To process data in the browser, you don’t need a form. Using a form just complicates things (though such issues could be fixed by using type=button in the button element, to prevent it from acting as a submit button).

<input type="text" id="willbeshown" value="">
<button onclick=
  "showResult(document.getElementById('willbeshown'))">Ganti1</button>
<p id="showresulthere">Result will be shown here</p>
<script>
function showResult(elem) {
  document.getElementById("showresulthere").innerHTML = Number(elem.value) + 2;
}
</script>

I have used conversion to numeric, Number(), as I suppose you want to add 2 to the field value numerically, e.g. 42 + 2 making 44 and not as a string, 42 + 2 making 422 (which is what happens by default if you just use an input element’s value and add something to it.

Solution 2

Your button should be

<button onclick="showResult(this.form); return false;">Ganti1</button>

Javascript

function showResult(form) {
  var coba=form.willbeshown.value;
  var coba2=coba+2;
  document.getElementById("showresulthere").innerHTML=coba2;
  return false; // prevent form submission with page load
}

DEMO

Share:
14,390
vinc
Author by

vinc

Newbie, Curious

Updated on June 06, 2022

Comments

  • vinc
    vinc almost 2 years

    I'm a newbie to scripting. I want to update HTML content with JavaScript, but as you can see the web page keeps refreshing.

    How can I prevent the page from refreshing?

    Javascript:

    function showResult(form) {
    var coba=form.willbeshown.value;
    var coba2=coba+2;
    document.getElementById("showresulthere").innerHTML=coba2;
    }
    

    HTML

    <form>
    <input type="text" name="willbeshown" value="">
    <button onclick="showResult(this.form)">Ganti1</button>
    </form>
    <p id="showresulthere">Result will be shown here</p>
    </body>
    
  • vinc
    vinc almost 12 years
    Helpful explanation, and works perfectly, many thanks! :) but what does 'elem' mean anyway?
  • Jukka K. Korpela
    Jukka K. Korpela almost 12 years
    In the code, “elem” is just a formal argument in the function and could be replaced by any free identifier. But the role of the argument is that it is an object representing an HTML element. The corresponding actual argument in the function call uses a method that gets an element by its id value.