如何限制多行輸入框的內容的長度

來源:互聯網
上載者:User

我們知道有的時候必須對文本輸入框的輸入長度進行限制,我們可以通過很簡單的maxlength 對Text 和 Password類型的輸入框的輸入長度進行限制,可是當我們對TextArea 使用maxlength 使用maxlength屬性的時候,我們遺憾的發現,這個屬性在textarea中是不起作用的有沒有辦法呢?答案是肯定的,有!就是使用HTC的技術,什麼是HTC??簡單的說,htc就是HTML Component,豆腐言語表達能力不強,我們看看下面的例子就可以了:

test.html:
  <form method="POST">
  <p><input type="text" size="30" maxlength="50" name="T1">
  <textarea name="S1" rows="4" cols="30" maxlength="50" style="behavior:url(maxlength.htc)"></textarea>
  </form>

大家注意到 以前很少見過 這樣的 用法: style="behavior:url(maxlength.htc)" 我們再看看下面的htc 的內容

<PUBLIC:COMPONENT id="bhvMaxlength" urn="maf:Maxlength">
  <PUBLIC:PROPERTY name="maxLength" />
  <PUBLIC:ATTACH event="onkeypress" handler="doKeypress" />
  <PUBLIC:ATTACH event="onbeforepaste" handler="doBeforePaste" />
  <PUBLIC:ATTACH event="onpaste" handler="doPaste" />

<SCRIPT language="JScript">
  // Keep user from entering more than maxLength characters
  function doKeypress(){
  if(!isNaN(maxLength)){
  maxLength = parseInt(maxLength);
  var oTR = element.document.selection.createRange();
  // Allow user to type character if at least one character is selected
  if(oTR.text.length >= 1)
  event.returnValue = true;
  else if(value.length > maxLength-1)
  event.returnValue = false;
  }
  }
  // Cancel default behavior
  function doBeforePaste(){
  if(!isNaN(maxLength))
  event.returnValue = false;
  }
  // Cancel default behavior and create a new paste routine
  function doPaste(){
  if(!isNaN(maxLength)){
  event.returnValue = false;
  maxLength = parseInt(maxLength);
  var oTR = element.document.selection.createRange();
  var iInsertLength = maxLength - value.length + oTR.text.length;
  var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
  oTR.text = sData;
  }
  }
  </SCRIPT>

</PUBLIC:COMPONENT>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.