Skip to content Skip to sidebar Skip to footer

Changing Div Content With Javascript OnClick

I'm trying to use a textbox and a submit button to change a div on the page. I want to take the text that has been typed in the textbox and put it in the div when the button is cli

Solution 1:

The problem is that the submit button is posting the form, so you are not seeing the change - If you change your submit button to a normal button it will work

<input type="button"name="button" id="button" onclick="myfunction()" /> 

Solution 2:

The form is submitting. You need to stop that by adding return false; (if you are using Jquery) Or remove the form entirely it is not required.

function myfunction() { 
    var myText = document.getElementById("textbox").value;
    document.getElementById('myDiv').innerHTML = myText;
    return false;
 } 

Solution 3:

Nothing happens because the form is being submitted. You need to prevent the default action from happening, which is the form submission. See preventDefault() or return false in the MDN for more details on how to prevent an events default action from occurring.


Solution 4:

Call event.preventDefault() to prevent the normal form submission.

function myfunction(e) { 
    e.preventDefault();
    var myText = document.getElementById("textbox").value;
    document.getElementById('myDiv').innerHTML = myText;
 } 

<form>
<input type="text" name="textbox" id="textbox" />
<input type="submit" name="button" id="button" onclick="myfunction(event)" />
</form>
<br/>
<div id="myDiv"></div>

Post a Comment for "Changing Div Content With Javascript OnClick"