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

javascript - set value of input element with jquery - Stack Overflow

programmeradmin1浏览0评论

I am trying to change the value of the inputfields with JQuery and I have no idea why this doesn't work. It does not throw an error but it just doesn't change. I'm building with appgyver steroids but i don't think that matters.

javascript:

$(document.getElementById("url")).val('test');

html

 <input type="text" id="url" class="topcoat-text-input"
       style="margin-left:10%; margin-top:10px; width: 80%; text-align: center" autocapitalize="off"
       autocorrect="off" required="true"
       placeholder="something else"/>

I am trying to change the value of the inputfields with JQuery and I have no idea why this doesn't work. It does not throw an error but it just doesn't change. I'm building with appgyver steroids but i don't think that matters.

javascript:

$(document.getElementById("url")).val('test');

html

 <input type="text" id="url" class="topcoat-text-input"
       style="margin-left:10%; margin-top:10px; width: 80%; text-align: center" autocapitalize="off"
       autocorrect="off" required="true"
       placeholder="something else"/>
Share Improve this question edited Mar 1, 2014 at 17:55 Brett DeWoody 63k31 gold badges144 silver badges192 bronze badges asked Jan 2, 2014 at 20:52 Daan LuttikDaan Luttik 2,8552 gold badges27 silver badges37 bronze badges 5
  • It works for me. jsfiddle/McTY3 – Kevin B Commented Jan 2, 2014 at 20:55
  • 1 $(document.getElementById("url")).val('test'); is excessive. if you want a jquery object use $("#url"). If you just want to change the value just use document.getElementById("url").value = "test". – scrappedcola Commented Jan 2, 2014 at 20:56
  • What point in the page load/user interfacing is this supposed to happen? Are you trying to have it change when an event occurs or just at the beginning of page load (...also an event lol) – Deryck Commented Jan 2, 2014 at 21:08
  • My guess (and It is a good one) is that you are loading the HTML in after you have loaded the page (ajax?) and therefore the js is not going to do anything. – rlemon Commented Jan 2, 2014 at 21:10
  • The html is in the page. its the very first file that is being loaded. – Daan Luttik Commented Jan 2, 2014 at 21:20
Add a ment  | 

1 Answer 1

Reset to default 5

Make sure that your code is running after the DOM is loaded.

Also there is no need for jQuery in your example.

You can just do:

window.onload = function(){
    document.getElementById("url").value = 'test';
};

Demo: http://jsfiddle/qwertynl/7uCfc/


And if you want to do full on jQuery:

$(function(){
    $('#url').val('test');
});

Demo: http://jsfiddle/qwertynl/m5Ttn/


Or you could not wrap your code in an onload and just put the whole script at the end of the document after the page has loaded already.

发布评论

评论列表(0)

  1. 暂无评论