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?
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?
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 "/>
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.
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);
});