[英]Adjusting the size of an input type text when content change
我有一個基本的輸入文本,用戶可以在其中輸入一些數字。 只要用戶鍵入數字,就可以調整輸入寬度(更大或更小)。
我的問題 :當數字不是直接鍵入而是通過代碼注入時,輸入寬度無法調整。
任何想法?
這是一個jsFiddle重現問題
第一:嘗試在輸入文本中輸入內容:您會看到此輸入寬度更大。
第二:嘗試單擊“確定”按鈕(將注入一些數字):您不會看到輸入寬度發生變化。
這是基本代碼:
<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);
謝謝。
只需觸發您已經設置的keyup
事件:
$('#myField').val('123456789123456789123456789').trigger("keyup");
無需進一步的代碼更改。 http://jsfiddle.net/moob/LkqTU/13540/
檢查這個1:-
$('#myField').val('123456789123456789123456789');
var a = $("#myField").val().length
$("#myField").attr('size', a);
alert(a);
您需要在input
字段中觸發change
事件以運行resizeInput()
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.