ShadowAccount
ShadowAccount

Reputation: 321

Automatically inserting window.location.hash into html input value?

Here's what I'm essentially trying to do:

<input type="text" class="form-control" value="window.location.hash">

What's the proper way to insert the window.location.hash into the input's value?

Note: I've found several ways to do this when people are required to click a button, but nothing that explains how to do it automatically when the page loads.

Upvotes: 0

Views: 382

Answers (3)

Kinglish
Kinglish

Reputation: 23664

You'll need to assign this after the page loads, or at least the element

<input type="text" class="form-control" id="hash" value="">
<script>
  window.onload=function() {
     document.querySelector("#hash").value = window.location.hash
  }
</script>

Upvotes: 1

Alcadur
Alcadur

Reputation: 685

You need JS script for that:

document.addEventListener('DOMContentLoaded', () => {
  const input = document.getElementById('location');
  input.value = window.location.host; // change .host to .hash
})
<input  id="location">

Upvotes: 0

user14550434
user14550434

Reputation:

Just get the element and change its value using JavaScript. In this Snippet, I'm redirecting to a different hash, just for example purposes.

const input = document.querySelector("input.form-control");

// Redirect to different hash for example
window.location.hash = "abcdef";

input.value = window.location.hash;
<input type="text" class="form-control" />

Upvotes: 0

Related Questions