Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  98] [ 7]  / answers: 1 / hits: 19945  / 12 Years ago, sat, june 9, 2012, 12:00:00

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>

More From » jquery

 Answers
19

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.


[#85024] Friday, June 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annaliese

Total Points: 86
Total Questions: 97
Total Answers: 107

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
;