Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM element disappearing immediately after update

I have the following javascript function that updates a text within a div when a button is clicked (using an onclick() event) It works, but it immediately changes back to the old text.

function func()
{
    var text = document.getElementById("text");
    text.innerHTML = "Changed";
};

The HTML

<body>
    <form>
        <input type="submit" value="Add Text" onclick="func()"/>
    </form>
    <div id="text">
        Text to Change
    </div>
</body>

What am I missing? I also tried returning 'false' from the function but no luck.

like image 484
kassold Avatar asked Nov 30 '22 02:11

kassold


1 Answers

You are actually submitting the form. Prevent that by adding return false to the onclick attribute:

<input type="submit" value="Add Text" onclick="func(); return false;"/>
like image 192
wanten Avatar answered Dec 04 '22 11:12

wanten