简体   繁体   English

如何使用CSS(或jQuery,如有必要)限制输入HTML输入的字符数?

[英]How can I restrict the number of characters entered into an HTML Input with CSS (or jQuery, if necessary)?

I can manipulate a control based on the state of another control, as shown in this jsfiddle , where the state of a Checkbox alters the width and background color of a Textbox. 我可以根据另一个控件的状态操作一个控件,如这个jsfiddle所示,其中Checkbox的状态改变了Textbox的宽度和背景颜色。

The HTML is: HTML是:

<input type="checkbox" id="ckbxEmp" >czech Bachs
<input type="text" id="txtbxSSNOrITIN">

The jQuery is: jQuery是:

$(document).on("change", '[id$=ckbxEmp]', function () {
    if ($(this).is(":checked")) {
        $('[id$=txtbxSSNOrITIN]').css('background-color', '#ffff00');
        $('[id$=txtbxSSNOrITIN]').css('width', '24');
    } else {
        $('[id$=txtbxSSNOrITIN]').css('background-color', 'green');
        $('[id$=txtbxSSNOrITIN]').css('width', '144');
    }
}); 

But besides this, what I really need to do is to restrict the number of characters the user enters into the Textbox, according to whether the checkbox's state. 但除此之外,我真正需要做的是根据复选框的状态来限制用户输入文本框的字符数。 How can I do that, preferably with CSS but, if necessary, jQuery? 我怎么能这样做,最好用CSS,但如果有必要,jQuery?

jsFiddle 的jsfiddle

First, set maxlength like: <input type="text" id="txtbxSSNOrITIN" maxlength="5"> 首先,设置maxlength如: <input type="text" id="txtbxSSNOrITIN" maxlength="5">

$(document).on("change", '[id$=ckbxEmp]', function () {

    var ckd = this.checked;                        // ckd is now a boolean 
    $('[id$=txtbxSSNOrITIN]')
        .attr("maxlength", ckd? 2 : 5)             // 2 characters if checked, else 5
        .css({
            background: ckd? '#ffff00' : "green",  // yellow if checked, else green
            width: ckd? 24 : 144                   // 24px if checked, else 144
        });

}); 

There's still a smaller issue above, and that's if ie: user enters initially more than 5 characters, if you click the checkbox the value length will still be 5! 上面还有一个较小的问题,那就是ie:用户最初输入超过5个字符,如果你点击复选框,值长度仍然是5! So you'll need an additional strip, to remove unwanted characters like: 因此,您需要一个额外的条带,以删除不需要的字符,如:

$(document).on("change", '[id$=ckbxEmp]', function () {

    var ckd = this.checked;
    $('[id$=txtbxSSNOrITIN]').attr("maxlength", ckd? 2 : 5).css({
       background: ckd? '#ffff00' : "green",
       width: ckd? 24 : 144
    }).val(function(i, v){
       // If checked, slice value to two characters:
       return ckd && v.length>2 ? v.slice(0,2) : v;
    });

}); 

If you want to go-pro with the code you build, you might want additionally 如果你想使用你构建的代码去专业 ,你可能还想要
prevent the user to feel stupid 防止用户感到愚蠢
by storing the last (the long one) typed value. 通过存储最后一个(长一个)类型的值。 If the user clicks the checkbox and than realizes "well... that was stupid" , by ticking it off again he should get back the old value: 如果用户点击该复选框,比实现“嗯......这是愚蠢的”,打勾就关闭一次他应该找回昔日的价值:

jsFiddle 的jsfiddle

$(document).on("change", '[id$=ckbxEmp]', function () {   

    var ckd = this.checked;
    var $input = $('[id$=txtbxSSNOrITIN]');
    if(ckd) $input.data("oldValue", $input.val() ); // Remember the current value

    $input.prop("maxlength", ckd? 2 : 5).css({
        background: ckd? '#ffff00' : "green",
        width: ckd? 24 : 144
    }).val(function(i, v){
        // If checked, slice value to two characters:
        return ckd && v.length>2 ? v.slice(0,2) : $input.data("oldValue");
    });

}); 

I don't think it's possible to do with CSS. 我不认为可以用CSS做。

The jquery/javascript approach would be set a default maxlength in the input field and then change it's attribute in the checkbox event. jquery / javascript方法将在输入字段中设置默认的maxlength,然后在checkbox事件中更改它的属性。 The numeric value can then be tied to a CSS property. 然后可以将数值绑定到CSS属性。

$('[id$=txtbxSSNOrITIN]').attr("maxlength", adjustedInputLengthVal );

you also have to crop the text if you're downsizing to a shorter length. 如果你缩小到较短的长度,你还必须裁剪文本。

reference: Can I specify maxlength in css? 参考: 我可以在css中指定maxlength吗?

This is not possible using CSS . 使用CSS无法做到这一点。 Just add the maxlength attribute to the input field via jQuery 只需通过jQuerymaxlength属性添加到输入字段

$(document).on("change", '[id$=ckbxEmp]', function () {
    if ($(this).is(":checked")) {
        $('[id$=txtbxSSNOrITIN]').css('background-color', '#ffff00');
        $('[id$=txtbxSSNOrITIN]').attr('maxlength', '24');
    } else {
        $('[id$=txtbxSSNOrITIN]').css('background-color', 'green');
        $('[id$=txtbxSSNOrITIN]').attr('maxlength', '144');
    }
}); 

You do that the same as you are doing the changes of styles: 你这样做就像你做样式的改变一样:

$('#txtbxSSNOrITIN').attr('maxlength', '2');

Notice also how I replaced the selector #txtbxSSNOrITIN . 另请注意我如何替换选择器#txtbxSSNOrITIN That's a better and faster approach to select by id. 这是一种更好,更快的方法来选择id。

$('#txtbxSSNOrITIN').attr('maxlength', '10');

This is what happens if the checkbox isn't checked (just an example) 如果未选中该复选框,则会发生这种情况(仅作为示例)

Don't forget to cut off the value entered by the user if the maxlength attribute gets contrained 如果maxlength属性受到限制,请不要忘记切断用户输入的值

$('#txtbxSSNOrITIN').val($('#txtbxSSNOrITIN').val().substr(0,2));

That happens in the if block. 这发生在if块中。 Here your fiddle modified: 在这里你的小提琴修改:

http://jsfiddle.net/jy6t5oru/7/ http://jsfiddle.net/jy6t5oru/7/

If you don't mind. 如果你不介意的话。 Take my method : maxlength 拿我的方法: maxlength

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

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

相关问题 jQuery限制可以输入到输入中的字符 - jQuery restrict characters that can be entered into input jQuery-如何允许数字键盘和数字键行输入; 以及防止输入特殊字符? - jQuery - How can I allow both numpad and number key row input; as well as prevent special characters from being entered? 如何使用jQuery限制输入到输入文本元素中的文本? - How can I restrict the text entered into an input text element using jQuery? jQuery:仅数字输入,但也限制字符数 - jquery: numeric input only, but also restrict number of characters 如何在jQuery中将输入限制为仅句点,数字和分号? - How can I restrict input to only periods, numbers and semicolons in jQuery? 如何限制要输入的文本框中的任何特定字符。 我只想限制 ^ 和 % - How to restrict any specific characters in textbox to be entered. I want to restrict only ^ and % 如何使用 jquery 阻止或限制来自输入字段的特殊字符? - How do I block or restrict special characters from input fields with jquery? Rails形式:如何限制输入字段中的字符数(数字) - Rails form: How to restrict number of characters (digits) in input field jQuery:如何限制字符数? - jQuery: How do I restrict number of chars? 输入5个字符后如何定位输入? - How do I target an input when 5 characters have been entered?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM