textarea中的字数限制-问题 [英] word limit in textarea - problem

查看:79
本文介绍了textarea中的字数限制-问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过以下形式限制文本区域的字数吗?

I want to make a word limit on textarea in the below form any body help me?

   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>freebacklinkcreator.blogspot.com submit form</title>
</head>
<body>

<form method="post" action="sendeail.php">

<!-- DO NOT change ANY of the php sections -->
<?php
$ipi = getenv("REMOTE_ADDR");
$httprefi = getenv ("HTTP_REFERER");
$httpagenti = getenv ("HTTP_USER_AGENT");
?>

<input type="hidden" name="ip" value="<?php echo $ipi ?>" />
<input type="hidden" name="httpref" value="<?php echo $httprefi ?>" />
<input type="hidden" name="httpagent" value="<?php echo $httpagenti ?>" />


Your Name: <br />
<select name="visitor" size="1">
<option value=" Business ">Business </option>
<option value=" Finance ">Finance </option>
<option value=" Reference ">Reference </option>
<option value=" Shopping ">Shopping </option>
<option value=" Arts and Entertainment ">Arts and Entertainment </option>
<option value=" Computers ">Computers </option>
<option value=" Health ">Health </option>
<option value=" News and Media ">News and Media </option>
<option value=" Regional ">Regional </option>
<option value=" Society ">Society </option>
<option value=" Education ">Education </option>
<option value=" Internet ">Internet </option>
<option value=" Recreation ">Recreation </option>
<option value=" Science and Technology ">Science and Technology </option>
<option value=" Sports ">Sports </option>
<option value=" Jobs ">Jobs </option>
<option value=" Online ">Online </option>
<option value=" Money ">Money </option>
<option value=" Affiliate Programs ">Affiliate Programs </option>
</select>
<br />
Your Email:<br />
<input type="text" name="visitormail" size="35" />
<br /> <br />
<br />
Site Title:<br />
<input type="text" name="attn" size="35" />
<br /><br />
Site Description:
<br />
<textarea name="notes" "rows="4" cols="40"></textarea>
<br />
<input type="submit" value="Send Mail" />
<br />
</form>

</body>
</html>

推荐答案

最近遇到了类似的问题...

Encountered a similar issue recently...

请参见下面和 codepen.io 上的演示:

See demo below and on codepen.io:

'use strict';

let WordLimiter = function(el){

  el.constraints = {

    /**
     * Events to listen to
     */
    eventListeners: [
        'keyup',
        'input'
    ],

    events: {
      onWordLimiterCount: new CustomEvent('onWordLimiterCount',{
        detail: {
           value: 0,
           words: []
        }
      })
    },

    limit: null,
    validValue: '',

    /**
     * Checks if the
     * @returns {boolean}
     */
    passed: function(){
      return this.wordCount() <= this.getLimit();
    },

    /**
     * Check if the element has a valid limit
     * @returns {boolean}
     */
    hasLimit: function(){
      return false !== this.getLimit();
    },

    getLimit: function(){
      this.limit = parseInt( this.element.dataset.wordLimit );
      this.limit = isNaN( this.limit ) || this.limit <= 0 ? false : this.limit;
      return this.limit;
    },

    getWords: function(){
      this.words = this.element.value.split(' ');

      /**
       * Removes words that are just empty strings
       */
      this.words = this.words.filter(function (el) {
        return el !== null && el.trim() !== '';
      });
      return this.words;
    },

    /**
     * Gets the word count
     * Also triggers an event that you can hook into
     * @returns {number}
     */
    wordCount: function(){
      this.events.onWordLimiterCount.detail.words = this.getWords();
      this.events.onWordLimiterCount.detail.value = this.getWords().length;
      document.dispatchEvent(this.events.onWordLimiterCount );
      return this.events.onWordLimiterCount.detail.value;
    },

    /**
     * Checks constraints
     * @returns {boolean}
     */
    verify: function(){
      console.clear();

      if( !this.constraints.passed() ){
        console.info( 'FAILED' );

        /**
         * Prevent any further input
         */
        event.preventDefault();
        event.stopPropagation();

        /**
         * Revert back to the last valid input
         * @type {string}
         */
        this.value = this.constraints.validValue;
        return false;
      }

      console.info( 'PASS' );
      this.constraints.validValue = this.value;
      return true;
    },

    /**
     * Scope purposes
     */
    element: el,
  };


  if( !el.constraints.hasLimit() ){
    console.groupCollapsed( 'TextArea does not have a valid limit' );
    console.info( el );
    console.groupEnd();
    return;
  }

  el.constraints.eventListeners.forEach(function(e){
    el.addEventListener(e, el.constraints.verify );
  });

};

/**
 * Looks for all textarea elements with the data-word-limit attribute
 */
document.addEventListener("DOMContentLoaded", function(){
  let textAreas = document.querySelectorAll("textarea[data-word-limit]");

  textAreas.forEach(function(i){
    new WordLimiter(i);
  });

}, true );

let CodePenDemo = {

  init: function(){
    document.addEventListener( 'onWordLimiterCount', function(e){
      document.getElementById('counter').value = e.detail.value;
    })
  },

  setWordLimit: function(){
    document.getElementById('textarea-limited').setAttribute( 'data-word-limit', event.srcElement.value );
  }
};

CodePenDemo.init();

<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
	<script src="index.js"></script>
</head>
<body class="bg-light">
    <div class="container my-3">
        <h2>TextArea with Word Limit</h2>

        <div class="form-group">
            <label for="word-limit">Word Limit</label>
            <input id="word-limit" type="number" min="1" class="form-control" value="50" onchange="CodePenDemo.setWordLimit();"/>
        </div>
        
        <div class="form-group">
            <label for="textarea-limited">TextArea</label>
            <textarea id="textarea-limited" class="form-control" data-word-limit="50" rows="10" cols="20"></textarea>
        </div>
        
        <div class="form-group">
            <label for="counter">Words Count</label>
            <input type="number" id="counter" class="form-control" />
        </div>
    </div>
</body>
</html>

这篇关于textarea中的字数限制-问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆