Mandriospo
Mandriospo

Reputation: 41

html input auto width

I want to use <input> as a editable box with auto width. This is what I did so far:

<div>
    <table>
        <tr>
            <td>aaaa</td>
            <td>bbbb</td>
        </tr>
        <tr>
            <td><input type="text" value="this_box_i_want_to_have_auto_td_width"/></td>
            <td><input type="text" value="sometextsometext"/></td>
        </tr>

    </table>
</div>

any idea how to make it resize when I type more text into input box?

Upvotes: 0

Views: 1232

Answers (2)

Richard Hamilton
Richard Hamilton

Reputation: 26444

$("input").on("keyup", function() {
    var length = $(this).val().length;
    if (length >= 10 && length < 20) {
        $(this).css({ "width": "200px" });
    } 
    else if (length >= 20 && length < 30) {
        $(this).css({ "width": "250px" });
    }
    else if (length >= 30) {
        $(this).css({ "width": "500px" });
    }
});
input {
  width: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" />

You will want to listen for the keyup event for determine the length of the text the user's entered. We can keep track of this with a length variable.

We will have multiple conditionals based on the length. We can adjust the width with the css property.

Upvotes: 1

Korgrue
Korgrue

Reputation: 3478

Set the text inputs to 100%. Give them a max width if you want, otherwise it will constrain to the width of your table columns. Remove all margin if you dont want it to overflow.

Alternately, width:auto; on the text fields will allow them to expand without overflow if you apply margins or padding. They should inherit the max width from the parent element.

Upvotes: 0

Related Questions