1

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?

2
  • 5
    well, if you're using a method called getElementById, wouldn't you expect the element you try to get to actually have an id ? Commented Jun 18, 2013 at 12:18
  • Add attribute id i.e. id="name" to input field Commented Jun 18, 2013 at 12:19

4 Answers 4

4

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;
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for answering. I've changed it to this: <script> var url = document.URL; url = url.slice(17,21); getElementById("name")=document.write="url" document.write="url"; </script> And <input id="name" name="name"/> But still nothing
@user2497085 see my above edit, that shows you how the js should look like
@user2497085 and dont forget to set the type to text
Thank you again for answering, turns out the thing I forgot to add was the window.onload
3

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"/>

1 Comment

YES! It works, thank you so much, you have no idea how much time I've wasted on this. Thank you!
1
<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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.