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

javascript - Scroll Width always returning undefined - Stack Overflow

programmeradmin0浏览0评论

I am doing a bit of program in which whenever it detects an input change in the textbox it needs to do something. But it doesn't work for me. So i Change i started giving the value in console to verify it whenever it detects a change in input it always returns undefined. How can i get the size of the text a user has entered in pixels?

<!doctype html>
<html>
<head>
<style>
    input[type=text] {
        height: 20px;
        width: 100px;
    }
</style>
<script src="jquery.js"></script>
</head>
<body>
    <input type="text" id="func"></input>
</body>
<script>
    $("#func").change(function () {
      console.log($("func").scrollWidth);
    });
</script>
</html>

I am doing a bit of program in which whenever it detects an input change in the textbox it needs to do something. But it doesn't work for me. So i Change i started giving the value in console to verify it whenever it detects a change in input it always returns undefined. How can i get the size of the text a user has entered in pixels?

<!doctype html>
<html>
<head>
<style>
    input[type=text] {
        height: 20px;
        width: 100px;
    }
</style>
<script src="jquery.js"></script>
</head>
<body>
    <input type="text" id="func"></input>
</body>
<script>
    $("#func").change(function () {
      console.log($("func").scrollWidth);
    });
</script>
</html>
Share Improve this question asked Jan 14, 2016 at 10:03 Ashok kumarAshok kumar 5421 gold badge5 silver badges22 bronze badges 1
  • 1 As other said scrollWidth has not wrapper in jQuery, So you can get it with $(selector).prop('scrollWidth'). – QMaster Commented Apr 17, 2018 at 17:15
Add a comment  | 

3 Answers 3

Reset to default 10

You have two bugs in your code. First, you select the element func without a hash. If you select an id in jQuery, you are required to use a # in front of the id name (see reference). So, you need to select it like this: $('#func').

Second, you need the DOM element of $('#func') and not its jQuery wrapper to access the property scrollWidth. You can do that by using $('#func')[0].scrollWidth or $('#func').get().scrollWidth.

I would however recommend you to use the jQuery width function to get the width of the input field: $('#func').width().

scrollWidth is a DOM-Element attribute, not a jQuery attribute, $('#func').get().scrollWidth should be defined.

const element = $("#func");

// Get the scroll width using the DOM element
const scrollWidth = element[0].scrollWidth;

console.log(scrollWidth);
发布评论

评论列表(0)

  1. 暂无评论