As Alien Webguy said , you are trying to call the jQuery ( val ) function on , which is probably a raw DOM or window element (you did not have enough context to find out what this , but the error tells us this is not like a jQuery instance ) the document object (because the one that jQuery sets this when calling your ready handler). (Your update made this clear.) So, first you need to get the correct link for the field and wrap it in a jQuery instance.
But separately, if you set size to the number of characters, the field will almost certainly be much larger than you want. This is because size works in uniform character widths.
Instead, it is common to measure the actual string using an out-of-page element with the same font family, style, size, decoration, etc. etc. as an input element. Something like this ( live copy ):
CSS
#theField, #measure { font-family: serif; font-size: 12pt; font-style: normal; } #measure { position: absolute; left: -10000px; top: 0px; }
HTML:
<input type='text' id='theField' value=''> <span id="measure"></span>
JavaScript:
jQuery(function($) { var field; // Hook up some events for resizing field = $("#theField"); field.bind("change keypress click keydown", function() { resizeIt(field); }); // Resize on load resizeIt(field); // Function to do the work function resizeIt(field) { var measure = $("#measure"); measure.text(field.val()); field.css("width", (measure.width() + 16) + "px"); } });
Please note that I also resize to different events; I doubt the list is comprehensive, but it gives you an idea.
source share