最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 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;

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 idattribute.

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

发布评论

评论列表(0)

  1. 暂无评论