Increase textbox size with Text

2019-08-07 02:15发布

问题:

I didn't know how to Google this, it always came up with answers I wasn't looking for. So, I have a textbox, I want it so that it has a set size BUT if the text is larger than the size then I want the textboxes size to increase with the Text.

Confusing Right? I'm not too good at explaining this stuff.

New Part: The textbox comes preloaded with this text, but the answers provided only work as they are typing. I can't find onload on the textbox, so what now?

回答1:

This worked for me:
http://www.codingforums.com/showthread.php?t=54130

Also run it on window load (this example is for an asp .net page):

<script type="text/javascript" language="JavaScript" src="../../javascript/Utility.js">
</script>

<script type="text/javascript" >
    window.onload = Init;

    function Init()
    {
      ResizeTextarea(document.getElementById("<%=tbDetails.ClientID%>"));
    }
</script>


回答2:

Maybe not perfect but here is very simple solution that works:

<input type="text" onkeyup="if (this.value.length > 20) this.size = this.value.length;" />

For prettier things you can Google for "Auto expanding textbox" although you'll find major of the stuff about textarea, not <input type="text" />,

Edit: to make it work onload, add such code to your page:

<script type="text/javascript">
window.onload = function() {
    var arrInputs = document.getElementsByTagName("input");
    for (var i = 0; i < arrInputs.length; i++) {
        var oCurInput = arrInputs[i];
        if (oCurInput.type == "text")
            oCurInput.onkeyup();
    }
};
</script>