0

How do I get a input field to have the value of the current webpage URL using Javascript?

My proposed approach:

<script>
    var holder = window.location.href;
</script>

<input id="moo" value= holder>
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
Bobshark
  • 376
  • 1
  • 3
  • 12

2 Answers2

3

To set the value of a text input field to the location of the current page, first, we have to set up the HTML correctly:

<input type="text" id="moo">

With JavaScript, we can easily select this element with a call to document.getElementById, passing in the id of the text field as a parameter:

var input = document.getElementById("moo"); // "moo" is the 'id' of the text field

Now, we can assign the value of the text field to location.href:

input.value = location.href;

Now our input field will contain the location of the current webpage.

var input = document.getElementById("moo"); // "moo" is the 'id' of the text field
input.value = location.href;
<input type="text" id="moo">
Hatchet
  • 5,320
  • 1
  • 30
  • 42
-1

HTML

<input type="text" id="url" placeholder="type the url to navigate to" />
<button id="search">
  search
</button>

JS

$(function() {
    $("#search").click(function() {
    var url = $("#url").val();

    window.location.href = url;
  });
});
Anwar
  • 4,162
  • 4
  • 41
  • 62