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

4

3 回答 3

1

是的,你可以做到这一点

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

});

和一个 CSS 类:

.mini{
    width:10px;
}

小提琴的例子。

希望能帮助到你!

于 2013-08-01T15:46:27.357 回答
0

试试下面的事情,如果我们说在某些字符限制之后将输入字段替换为 textarea,请参见以下代码:

$(".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()));
    }
});

这里的工作示例:http: //jsfiddle.net/tFDNx/2/

于 2013-08-01T16:04:46.900 回答
0

你可以使用它们中的任何一个,这一切都很好

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();
  });
});
于 2013-08-01T16:21:50.683 回答