0

One very basic question about <input type='text'> in HTML.

I currently have a database, and I am using javascript/ajax to set the value from the database into the textbox.

In a normal situation, any text inside the textbox will fit in nicely, like in this picture.

In a non-normal situation, I can have a very long string set inside the textbox, like in this picture

I am wonder if there any sort of javascript/css functionality that I am not aware of. Such that I can 'dynamically' increase the width of the <input type='text'> or the padding inside the <input type='text'> such that that textbox can hold a long string relatively nicely?

I am not sure if my question is absurd in such a sense that we never know the length of the string that I am going to fetch from the database. So it seems unlikely that I can know by how much I can increase the width of the textbox.

Thank you in advance.

jin cheng teo
  • 195
  • 1
  • 13
  • 2
    check out this topic "https://stackoverflow.com/questions/30520858/dynamically-adjust-html-text-input-width-to-content?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa", i think it's just want you want. – jorgehvieirasilva Jun 06 '18 at 10:22
  • @jin cheng teo : did you got the solution from post link shared by jorgehvieirasilva – AmanKumar Jun 06 '18 at 10:42

1 Answers1

0

html:

<input type="text" class="width-dynamic proba dva" placeholder="Type text here to test."/>

jQuery

$.fn.textWidth = function(text, font) {

if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);

    $.fn.textWidth.fakeEl.text(text || this.val() || this.text() || this.attr('placeholder')).css('font', font || this.css('font'));

    return $.fn.textWidth.fakeEl.width();
};

$('.width-dynamic').on('input', function() {
    var inputWidth = $(this).textWidth();
    $(this).css({
        width: inputWidth
    })
}).trigger('input');


function inputWidth(elem, minW, maxW) {
    elem = $(this);
    console.log(elem)
}

var targetElem = $('.width-dynamic');

inputWidth(targetElem);

https://codepen.io/samgray75/pen/NzvyBx

Sam
  • 127
  • 1
  • 3
  • 9