0

I have a form with a ton of text boxes in and rather than set the size for each text box manually, I was hoping I could set the size to the contents of the text boxes on page load.

I have found a good auto grow script here Is there a jQuery autogrow plugin for text fields?

but do not know how to make them default smaller if theres say only 1 character in the textbox

Thanks

Community
  • 1
  • 1
AlexW
  • 2,843
  • 12
  • 74
  • 156

3 Answers3

1

Yes, you can do it with

$("input").each(function(){
    var myLength = $(this).val().length;
    if(myLength == 1){
        $(this).attr('size', myLength);
        $(this).attr('class', 'mini');
    }else{
        $(this).attr('size', myLength);    
    }

});

and a css class:

.mini{
    width:10px;
}

Example on fiddle.

Hope it helps!

Lan
  • 709
  • 1
  • 8
  • 16
  • this gives me error SCRIPT380: Invalid property value. jquery-1.8.2.min.js, line 2 character 32075 SCRIPT257: Could not complete the operation due to error 80020101. – AlexW Aug 01 '13 at 16:23
  • it's a problem with your jquery version; in jsfiddle I used the 1.9.1. Your version it's the 1.8.2 :) – Lan Aug 01 '13 at 16:24
  • Remember to download always the last version of jQuery.. I didn't used the last one.. but seems it works on 1.9.1 – Lan Aug 01 '13 at 16:28
  • looks like the problem is with another jquery pluggin you may have in the page. Try to isolate the scripts until you found the trouble.. :) – Lan Aug 02 '13 at 10:11
0

try following thing, what if we say after some characters limit will replace input field to textarea, see following code:

$(".input_text").each(function(index, obj){
    var txt = $(this), txtLength = txt.val().length;
    if(txtLength <= 1){
        txt.height("25px");
    }else{
        var txtarea = $("<textarea/>");
        txt.replaceWith(txtarea.val(txt.val()));
    }
});

Working example here: http://jsfiddle.net/tFDNx/2/

maverickosama92
  • 2,685
  • 2
  • 21
  • 35
0

You can use any of them this all works fine

1) <input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">

2) var inputEl = document.getElementById("theInput");

  function getWidthOfInput() {
    var tmp = document.createElement("span");
    tmp.className = "input-element tmp-element";
    tmp.innerHTML = inputEl.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    document.body.appendChild(tmp);
    var theWidth = tmp.scrollWidth;
    document.body.removeChild(tmp);
    return theWidth;
  }

  function adjustWidthOfInput() {
    inputEl.style.width = getWidthOfInput() + "px";
  }

  adjustWidthOfInput();
  inputEl.onkeyup = adjustWidthOfInput;

3) // HTML // jQuery

$(function(){
  $('#input').keyup(function(){
    $('<span id="width">').append( $(this).val() ).appendTo('body');
    $(this).width( $('#width').width() + 2 );
    $('#width').remove();
  });
});
GeniusJRS
  • 119
  • 2
  • 6