7

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>
Ashok kumar
  • 544
  • 1
  • 5
  • 21
  • 1
    As other said scrollWidth has not wrapper in jQuery, So you can get it with $(selector).prop('scrollWidth'). – QMaster Apr 17 '18 at 17:15

2 Answers2

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().

ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
  • 1
    I need to get the size of the pixels of the input no the whole inputbox size? – Ashok kumar Jan 14 '16 at 10:32
  • 1
    There is no such function available to get the width of the input field content. There are however some approches here: http://stackoverflow.com/questions/3392493/adjust-width-of-input-field-to-its-input and here: http://stackoverflow.com/questions/9328682/jquery-resizing-form-input-based-on-values-width – ssc-hrep3 Jan 14 '16 at 10:53
  • 2
    I know this is somewhat old, but `$('#func').get().scrollWidth` will return "undefined" if you don't specify the index, so when getting the first element, using index 0, it should be `$('#func').get(0).scrollWidth` – YTZ Sep 29 '19 at 14:09
2

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

user3154108
  • 1,264
  • 13
  • 23