0
<form>

<p>Enter Title Text:</p>
<input type="text">
<button onclick="hello()">Submit</button>
</form>
</body>

<script>

function hello() {


  document.querySelector("title").textContent =
  document.querySelector("input").value;


}

My intent is for the tab title to change to the text the user entered upon clicking the button. I think it is working but only for a split second then changing back. Any help is greatly appreciated. Thanks!

evanr123
  • 65
  • 1
  • 1
  • 7

2 Answers2

-1

Change the button's type to "button" so clicking it does not submit the form. The default type for a button inside a form is "submit", which will cause it to submit the form and hence reload the page when it is clicked. Explicitly setting the type prevents this behavior.

See also: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

<button type="button" onclick="hello()">Submit</button>

function hello() {
  document.querySelector("#result").textContent = "Title text is: " + document.querySelector("input").value;
}
<form>
<p>Enter Title Text:</p>
<input type="text">
<button type="button" onclick="hello()">Submit</button>
</form>
<p id="result">
</p>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
-1

Here is the solution:-

<form onsubmit="event.preventDefault()">
  <p>Enter Title Text:</p>
  <div class="title"></div>
  <input type="text">
  <button onclick="hello()">Submit</button>
</form>

function hello() {
  document.querySelector(".title").innerHTML =
  document.querySelector("input").value;
}

First, you need to prevent the default behaviour of form by using preventDefault or just omit form tag it works the same in both cases, in order to use "onclick" event of your button
Then, for getting the desired result you can use innerHTML like I have used here.

Paras Agrawal
  • 21
  • 1
  • 3