I'm trying to have jQuery test the length of the text in the input box onLoad and change the size of the input box to fit. Here is my code attempt so far:
$("#emailSubject").attr('size', this.val().length);
I'm getting the following error:
this.val is not a function
What am I doing wrong?
Update: Now I'm no longer getting the first error, but the length is showing up as 0 even though it's not supposed to be. (I'm using an alert to check what the length is). Why would that be happening?
Update: Here is the code context:
$(
function()
{
//works correctly
alert($("#emailSubject").val().length);
//throws error
$("#emailSubject").attr('size', ($(this).val().length));
}
)
New error- the length is showing up correctly in the alert, but I'm getting the error:
Index or size is negative or greater than the allowed amount.
You
arewere using$(this)
in a confusing way here because we can't see how the rest of the code comes into play.For example:
In the code above,
$(this)
refers to$('body')
and you would need to do something like this:If, however, your event handler was bound to
$('#emailSubject')
then$(this)
would work, and you could even use it twice:You need to surround the
this
into a jQuery object$(this)
As Alien Webguy said, you're trying to call a jQuery function (
val
) onwhat's probably a raw DOM element or thethewindow
object (you haven't shown enough context for us to know whatthis
is, but the error tells us it's not a jQuery instance)document
object (because that's what jQuery setsthis
to when calling yourready
handler). (Your update clarified it.) So the first thing is to get the correct reference 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. That's becausesize
works in uniform character widths.Instead, the usual thing is to measure the actual string using an off-page element with the same font family, style, size, text decoration, etc., etc. as the input element. Something like this (live copy):
CSS:
HTML:
JavaScript:
Note that there I'm resizing on various events as well; I doubt the list there is comprehensive, but it gives you an idea.