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?
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?
Share Improve this question edited Jun 18, 2013 at 12:21 mrz 1,8722 gold badges21 silver badges33 bronze badges asked Jun 18, 2013 at 12:15 HoloLadyHoloLady 1,0431 gold badge12 silver badges28 bronze badges 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 ? – Laurent S. Commented Jun 18, 2013 at 12:18
- Add attribute id i.e. id="name" to input field – vivek salve Commented Jun 18, 2013 at 12:19
4 Answers
Reset to default 4Change 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;
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"/>
<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 id
attribute.
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