简体   繁体   中英

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 clicked. I have this code:

 function myfunction() { 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()" /> </form> <br/> <div id="myDiv"></div> 

But nothing happens. When I try it in the browser it just refreshes the page and adds ?textbox=someValueHere to the end of the URL. How can I get the div to display the textbox value?

问题是提交按钮正在发布表单,因此您没有看到更改 - 如果您将提交按钮更改为普通按钮,它将起作用

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

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.

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>

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;
 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM