-1

I have a input field which is having some fixed width. (Ex: 200px) and Placeholder text is having more letters.

How can I dynamically change width of the input field based on the placeholder text/width?

Renuka CE
  • 666
  • 1
  • 6
  • 15
  • Based on this [answer](https://stackoverflow.com/questions/30520858/dynamically-adjust-html-text-input-width-to-content/30520997) you can do this : $('input').css('width',((input.getAttribute('placeholder').length + 1) * 8) + 'px'); – Sfili_81 May 29 '18 at 06:37
  • duplicate:https://stackoverflow.com/q/17302794/3098803 – Ali May 29 '18 at 07:02

3 Answers3

1

set size to input

var inputs = document.getElementsByTagName('input');
for(i=0; i<inputs.length; i++){
    inputs[i].setAttribute('size',inputs[i].getAttribute('placeholder').length);
}
<input placeholder="I am a long text...I am a long text...I am a long text "/>
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
0

Here's link to how you can do it - https://jsfiddle.net/4s03razg/

<div>
    <script>
        var prevLen = 50;
        window.resizeBox = function() {
            var elem = document.getElementById("resizable-input");
            if(elem.value && elem.value.length > 5) {
                prevLen += 10;
                elem.style.width = prevLen + "px";      
            }
        };

        function initializeBox() {
            var elem = document.getElementById("resizable-input");
            elem.style.width = prevLen + "px";
        }
        initializeBox();
    </script>
    <input id="resizable-input" type="text" onkeypress="resizeBox()"/>
</div>

This is just an example. You will have to use correct numbers and events to trigger the resizing. And you should better fetch the element using 'this' in method call through event, I think.

-1

you can do that using javascript or jquery, fetch the length of placeholder and then assign it to the input size; JS Code:

input.setAttribute('size',input.getAttribute('placeholder').length);

or, JQuery:

$("input[placeholder]").each(function () {
        $(this).attr('size', $(this).attr('placeholder').length);
    });