gpt4 book ai didi

javascript - 达到 maxlength 后如何限制输入的字符?

转载 作者:行者123 更新时间:2023-12-03 06:20:29 30 4
gpt4 key购买 nike

我有一个带有特殊符号按钮的输入作为附加组件。

HTML

<div class="col-md-3 col-xs-9 col-sm-9">
<div class="input-group">
<input type="text" maxlength="10" class="form-control" id="symboltext"> <span class="input-group-btn">
<button class="btn btn-default" type="button" id="popbutton" data-placement="bottom" data-container="body"><span class="glyphicon glyphicon-edit"></span>
</button>
</span>
</div>
</div>

JQuery

var popupElement = '<div class="btn-group" role="group"><button class="btn btn-sm btn-default" id="regbtn"><span class="glyphicon glyphicon-registration-mark"></button><button class="btn btn-sm btn-default" id="copyrightbtn"><span class="glyphicon glyphicon-copyright-mark"><span></button><button class="btn btn-sm btn-default" id="trademarkbtn"><sup>TM</sup></button></div>';
var lastPoint = 0;
$('#popbutton').popover({
animation: true,
content: popupElement,
html: true
});

function textbox() {
var ctl = document.getElementById('symboltext');
var startPos = ctl.selectionStart;
var endPos = ctl.selectionEnd;
lastPoint = startPos;
return {
s: startPos,
e: endPos
};
}

function getVal(insert) {
var val = $("#symboltext").val();
var index = textbox();
val = val.slice(0, index.s) + insert + val.slice(index.s)
lastPoint += 1;
return val;
}

$(document).on('click', "#trademarkbtn", function() {
var val = getVal("\u2122");
var input = $("#symboltext");
input.val(val).focus();
input[0].selectionStart = input[0].selectionEnd = lastPoint;
});


$(document).on('click', "#regbtn", function() {
var val = getVal("\u00AE");
var input = $("#symboltext");
input.val(val).focus();
input[0].selectionStart = input[0].selectionEnd = lastPoint;
});

$(document).on('click', "#copyrightbtn", function() {
var val = getVal("\u00A9");
var input = $("#symboltext");
input.val(val).focus();
input[0].selectionStart = input[0].selectionEnd = lastPoint;
});

我已将输入的最大长度设置为 10。但达到此值后,我仍然可以使用附加/特殊符号按钮输入字符。

Updated Fiddle

最佳答案

使用这个

<input id="field" type="text" maxlength="10" />

Jquery

$('#field').keypress(function (event) {
if ($('#field').val().length <= 10) {

if (event.keyCode != '110' && event.charCode != '46') {
$('#field').attr('maxlength', '09');
} else if (event.keyCode == '110' || event.charCode == '46') {
$('#field').attr('maxlength', '11');
}
}
});

关于javascript - 达到 maxlength 后如何限制输入的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38894545/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com