如何使用 jquery/javascript 更改某些元素的 maxlength?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20990518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:46:37  来源:igfitidea点击:

How to change maxlength of certain element using jquery/javascript?

javascriptjquery

提问by Frank Martin

I have the following element:

我有以下元素:

<input name="someelement" title="Title" class="someclass" id="someid" maxlength="255" value="Some Value" />

I want to change its length to 100. Can I do something like?

我想将其长度更改为 100。我可以做类似的事情吗?

document.getElementById("someid").maxlength = 100;

回答by Ludovic Guillaume

$('input[name="someelement"]').attr('maxlength', 100);

or

或者

$('input.someclass').attr('maxlength', 100);

or like tanaydin said :

或者像 tanaydin 说的:

$('#someid').attr('maxlength', 100);

回答by Krish R

You can use javascriptmaxLengthproperty

您可以使用javascriptmaxLength属性

document.getElementById("someid").maxLength = 100;

Ref: https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement

参考:https: //developer.mozilla.org/en/docs/Web/API/HTMLInputElement

回答by Abhitalks

To answer second part of your question:

回答问题的第二部分:

Javascript:

Javascript:

document.getElementById("someid").maxLength = "100";

JQuery:

查询

$('#someid').attr('maxlength', 100);

Note:

注意

  1. It is maxLength(uppercase L).
  2. The value better be provided as string (in quotes) although the attribute itself is implemented as Long.
  1. 它是maxLength(大写 L)。
  2. 尽管属性本身实现为 Long,但最好将值作为字符串(在引号中)提供。

回答by Ashish Kumar

Yes, you can!

是的你可以!

Using JavaScript:

使用 JavaScript:

document.getElementById("someid").setAttribute("maxlength", 100);

or

或者

document.getElementById("someid").maxLength = 100;

Using jQuery:

使用jQuery:

$('#someid').attr('maxlength', 100);

Good luck!

祝你好运!