How To Update/change Html Content With Javascript And Prevent The Page From Refreshing?
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).
<inputtype="text"id="willbeshown"value=""><buttononclick=
"showResult(document.getElementById('willbeshown'))">Ganti1</button><pid="showresulthere">Result will be shown here</p><script>functionshowResult(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
<buttononclick="showResult(this.form); return false;">Ganti1</button>
Javascript
functionshowResult(form) {
var coba=form.willbeshown.value;
var coba2=coba+2;
document.getElementById("showresulthere").innerHTML=coba2;
returnfalse; // prevent form submission with page load
}
Solution 3:
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:
<formonsubmit="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.
Solution 4:
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"
Post a Comment for "How To Update/change Html Content With Javascript And Prevent The Page From Refreshing?"