HoloLady
HoloLady

Reputation: 1043

How to set the value of an HTML input field with a javascript value

I know this has been asked a thousand times but nothing I've tried has worked so far. I'd really appreciate some input. Here's my situation, I have this code in javascript:

<script>
var url = document.URL;
url = url.slice(17,21);
</script>

I need the value of url in a html input field which looks like this:

<input name="name" type="text"/>

I've tried with getElementbyId and it shows me nothing.

Is there something I've missed?

Upvotes: 1

Views: 4952

Answers (4)

LuigiEdlCarno
LuigiEdlCarno

Reputation: 2415

<script type="text/javascript">
   var url = document.URL;
   url = url.slice(17,21);
   var urlField = document.getElementsByName('name')[0];
   url.value=url;
</script>

This assumes, that you have only one tag with name-attribute = "name", though. Else add an idattribute.

Upvotes: 1

Prabhuram
Prabhuram

Reputation: 1268

You can do it as follows :

<script>
      window.onload=function(){
        var url = document.URL;
        url = url.slice(17,21);
        document.getElementById("urlText").value=url;
      }          
</script>

In the HTML input tag change it as ,

<input id="urlText" name="name" type="text"/>

Upvotes: 3

Praveen
Praveen

Reputation: 56501

Try the below one. HTML:

<input id="textBox" type="text"/>

Javascript:

var url = document.URL;
url = url.slice(17,21);
document.getElementById("textBox").value = url;

Check this JSFiddle

Upvotes: 0

Johan
Johan

Reputation: 8256

Change your html to look like this, you forgot to set the id.

<input id="name" name="name" type="text"/>

and then your js will look like this

    var url = document.URL;
    url = url.slice(17,21);
    document.getElementById("name").value = url;

Upvotes: 4

Related Questions