views:

1843

answers:

4

Hi, I have the following bit of code to create an automatically resized text input:

// setup quick jump input
$("#goto").keydown(function(e){
  var size = $(this).val().length;

  // sanity
  if ( size < 1 ) {
    size = 1;
  }

  $(this).attr("size",size);

  // if enter then GOTO->
  if ( e.keyCode == 13 ) {
    window.location.href = "/" + $(this).val();
  }
});

HTML:

<input type="text" id="goto" size="1" name="goto" />

Problem: Resizing the input doesn't work in Safari or Chrome, just Firefox and Opera. I'm using jquery 1.3.2 and would like to know if it's a bug in jquery or my implementation.

EDIT: sorry I wasn't clear enough at first - it's the part where I'm trying to update the size of the input on the fly that is broken. My bad. Thanks for the feedback so far, some very useful links there.

+1  A: 

According to the jQuery documentation on keydown():

// Different browsers provide different codes
// see here for details: http://unixpapa.com/js/key.html    
// ...

Have you checked the page referenced to see if Safari/Chrome/Webkit have different values for the Enter key?

matt b
It might be worthwhile to check out http://www.quirksmode.org/js/keys.html They explain the differences and shortcomings of key events in the browsers. Enter should work as keycode 13 in all browsers according to my link though.
Ben S
+1  A: 

The problem seems to lie in setting the size attribute. This line:

$(this).attr("size",size);
Matt
I've tried making sure that size is a string but I can't figure out what's wrong with that line. The syntax is right... I guess the problem browsers 'protect' input attributes or something like that. Most upsetting.
sanchothefat
Yeah I tried setting the property directly with a string and a number, many different ways. It doesn't budge no matter what.
Matt
+1  A: 

I doubt that the size attribute would work cross browser. I would switch to setting the maxlength and css width of the input field rather than changing the size attribute.

Looks like a bug/unsupported feature in webkit. Which Safari/Chrome share.

Chad Grant
Thanks - I didn't think to just use CSS!
sanchothefat
+1  A: 

Safari nor Chrome doesn't respect some attributes. But you can set it via css element. Works good.

$(this).css("width","4em");

For example, i have noticed that onClick attribute doesn't work in Chrome when onclick is typed.

Jirka Kopřiva