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

<inputtype="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.

functionmyfunction() { 
    var myText = document.getElementById("textbox").value;
    document.getElementById('myDiv').innerHTML = myText;
    returnfalse;
 } 

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.

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

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

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