vinc
vinc

Reputation: 95

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

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>

Upvotes: 3

Views: 24118

Answers (4)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201538

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.

Upvotes: 2

Andreas
Andreas

Reputation: 21881

If you define a <button /> without defining its type it will work like a submit button. Just add type="button" to your button markup and the form won't be submitted.

<button type="button" onclick="showResult(this.form)">Ganti1</button>

With this change you won't need any return false or .preventDefault() "workarounds"

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173542

The others will explain how you should use jQuery, but this would explain why it didn't work in your original code.

The <button> tag submits the form, so you have to add this inside your form tag to prevent form submission:

<form onsubmit="return false">

Btw, even without giving your form an explicit action, it uses the current page to submit; it's easy to think that it will not do anything without an action.

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

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

Upvotes: 2

Related Questions