I am trying to add an click
event when I click on the button, and the page will show what I have typed into the input field:
var input = document.querySelector("input").value;
document.querySelector(".myButton").addEventListener("click",function()
{
var container = document.querySelector(".contanier");
container.innerHTML = input;
});
this is just work fine, but i want make this code looks strunctre a bit, so i rewite as :
var input = document.querySelector("input").value;
var button = document.querySelector(".myButton");
var container = document.querySelector(".contanier");
button.addEventListener("click",function(){container.innerHTML = input;});
but when I click the button the page just refresh to be blanked, do i have to make DOM inside the event
so this can work? Could anyone tell me what's the difference after I rewrite this?
sorry i fogort the html code:
<body>
<div class="main-container">
<input type="text" class="js-userInput">
<button class="myButton">Go!</button>
</div>
<div class="container"></div>
</body>
If you are trying this into the form then button should have the attribute type="button"
. Their another method in function ($event) { $event.preventDefault();}
. Example https://plnkr.co/edit/1F5Z7CZOS4P89nEzU7dP?p=preview
If you don't specify a type on a <button>
tag, it defaults to type="submit
, which causes the form the button belongs to to be submitted to the server.
This causes the same page to reload if a action
pointing to another URL was not set. If you add type="button"
it will function as a button without submitting the page. As nnnnnn noted in the comments, you also only get the value of the input box once, on page load, so even with type=button
it wouldn't work as intended.
When you grab .value
, you are grabbing a string containing it's value, not a reference to the .value
property. Instead store a reference to the element and grab the .value
every time your event handler runs.
var input = document.querySelector("input"), // store a reference to the element, // instead of querying the .value button = document.querySelector(".myButton"), container = document.querySelector(".container"); // there was a typo in the // class name here too, so // the container variable was null. button.addEventListener("click", function() { container.innerHTML = input.value; // query the .value here each time it runs });
<div class="main-container"> <input type="text" class="js-userInput"> <!-- you need to specify type button so it doesn't default to submit, which will reload the page. --> <button type="button" class="myButton">Go!</button> </div> <div class="container"></div>
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.