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

javascript - Get value of dom element in ready function - Stack Overflow

programmeradmin9浏览0评论

I want my textArea to resize when the page is fully loaded. I found that

$(document).ready(function() {
  // Handler for .ready() called.
});

can help me, so I try to test it and put next code into that function:

$(document).ready(function() {
      var element = $('#elementId');
      alert(element.value);
});

But when the page is loading, alert shows undefined value of textArea, however there is text inside it. How can I fetch those value inside ready function?

I want my textArea to resize when the page is fully loaded. I found that

$(document).ready(function() {
  // Handler for .ready() called.
});

can help me, so I try to test it and put next code into that function:

$(document).ready(function() {
      var element = $('#elementId');
      alert(element.value);
});

But when the page is loading, alert shows undefined value of textArea, however there is text inside it. How can I fetch those value inside ready function?

Share Improve this question asked Mar 15, 2013 at 16:57 maksmaks 6,00619 gold badges84 silver badges127 bronze badges 1
  • 1 $() returns a jQuery object so you need to execute jQuery methods on it to get to the value, ie: element.val() or get the underlying reference to the DOM element and use element[0].value. – Nope Commented Mar 15, 2013 at 17:04
Add a ment  | 

3 Answers 3

Reset to default 5
$(document).ready(function() {
      var element = $('#elementId');
      alert(element.val());
});

element isn't a DOM element but a jQuery wrapped object, it doesn't have any value property.

Use

$(document).ready(function() {
      var element = $('#elementId');
      alert(element.val());
});

or

$(document).ready(function() {
      var element = document.getElementById('elementId');
      alert(element.value);
});

or

$(document).ready(function() {
      var element = $('#elementId');
      alert(element.get(0).value);
});

You need to use DOM object to use value property and you have jQuery object you need to use val() on it.

$(document).ready(function() {
      var element = $('#elementId');
      alert(element[0].value);
      //or  
      alert(element.val());           
});
发布评论

评论列表(0)

  1. 暂无评论