0

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?

1
  • js code to fire onchange/onkeyup, calculate the size of the string in the box, and adjust the box's width as appropriate. Commented Nov 30, 2015 at 20:49

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I would also 1.) listen to the change event .on("keyup change..." to capture when the user pastes/deletes text with the mouse and 2.) have a condition for when length < 10 to return the box to it's original size
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.