shane Johnson
shane Johnson

Reputation: 69

Change HTML Document Title from Form input

I am trying to change a HTML page's title based on form input. This is needed because the page will be printed as a PDF and we want it to be saved as the customer's name + caller.)

I know the following code will change the document's title.

onClick="document.title = "My new title";

But I'm trying to do something like:

onClick="document.title = document.getElementById("customerName").value +" " + "Caller" ;"

Here is an example form:

<form action="">
  <label for="customerName">Customer name:</label><br>
  <input type="text" id="customerName" name="customerName" ><br>
  <input type="submit" value="Submit" onClick="document.title = document.getElementById("customerName").value +" " + "Caller" ;">
</form> 

Upvotes: 0

Views: 560

Answers (3)

Isaac Welch
Isaac Welch

Reputation: 163

document.title = document.getElementById('customerName').value +' ' + 'Caller' ;

Upvotes: 2

Dolev Dublon
Dolev Dublon

Reputation: 931

To give you the answer just try this code and see what i did different :)

let handleSubmit = (event) => {
  event.preventDefault()
  document.title = document.getElementById("customerName").value + " " + "Caller";
}
<form action="#" onsubmit="handleSubmit(event)">
  <label for="customerName">Customer name:</label><br>
  <input type="text" id="customerName" name="customerName"><br>
  <input type="submit" value="Submit">
</form>

Upvotes: 1

mplungjan
mplungjan

Reputation: 177796

You have quote issues. Also use the submit event instead of click

document.getElementById("form1").addEventListener("submit", function(e) {
  e.preventDefault(); // remove if you DO want the form to submit
  document.title = document.getElementById("customerName").value + " " + "Caller";
})
<form action="" id="form1">
  <label for="customerName">Customer name:</label><br>
  <input type="text" id="customerName" name="customerName"><br>
  <input type="submit" value="Submit">
</form>

Upvotes: 2

Related Questions