简体   繁体   English

内容更改时调整输入类型文本的大小

[英]Adjusting the size of an input type text when content change

I have a basic input text where user can enter some numbers in it. 我有一个基本的输入文本,用户可以在其中输入一些数字。 As long as user type numbers, the input width is adjusted (bigger or smaller). 只要用户键入数字,就可以调整输入宽度(更大或更小)。

My problem : when the numbers are not directly typed but injected by code, the input width is not adjusted. 我的问题 :当数字不是直接键入而是通过代码注入时,输入宽度无法调整。

Any idea? 任何想法?

Here is a jsFiddle to reproduce the problem 这是一个jsFiddle重现问题

1st: try to type something in the input text: you'll see this input width bigger. 第一:尝试在输入文本中输入内容:您会看到此输入宽度更大。

2nd: try to click on the Ok button (which inject some numbers): you'll not see the input width changing. 第二:尝试单击“确定”按钮(将注入一些数字):您不会看到输入宽度发生变化。

Here is the basic code: 这是基本代码:

<input type="text" id="myField" size="5">
<input type="button"Value="Ok" data-bind="click: buttonClicked">


var ViewModel = function(first, last) {

    this.buttonClicked = function() {           
        $('#myField').val('123456789123456789123456789');
        alert('Some numbers are directly injected but the input text is not adjusted');
    }  
};

ko.applyBindings(new ViewModel()); 

function resizeInput() {
    $(this).attr('size', $(this).val().length);
}

$('input[type="text"]')
        // event handler
        .keyup(resizeInput)
        // resize on page load
        .each(resizeInput);

Thanks. 谢谢。

Just trigger the keyup event you already have in place: 只需触发您已经设置的keyup事件:

$('#myField').val('123456789123456789123456789').trigger("keyup");

No further code changes required. 无需进一步的代码更改。 http://jsfiddle.net/moob/LkqTU/13540/ http://jsfiddle.net/moob/LkqTU/13540/

Check this 1 :- 检查这个1:-

http://jsfiddle.net/QZBda/ http://jsfiddle.net/QZBda/

        $('#myField').val('123456789123456789123456789');
        var a = $("#myField").val().length
        $("#myField").attr('size', a);
        alert(a);

You need to trigger a change event in the input field to run the resizeInput() function. 您需要在input字段中触发change事件以运行resizeInput()函数。

See this demo 看这个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM