Limit <textarea> length without losing caret position

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?ISO-8859-1?Q?=22=C1lvaro_G=2E_Vicario=22?=

    Limit <textarea> length without losing caret position

    I need to emulate the missing "maxlegth" attribute in "textarea" fields
    but all my Google searches either lead to obsolete scripts that
    overwrite the "value" property (thus losing caret position) or to
    complex solutions that work on top of specific frameworks.

    Do you have some reference on how to do it? I'd like to make it work in
    at least Firefox and IE 6 and 7.

    Thank you in advance,


    --
    -- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
    -- Mi sitio sobre programación web: http://bits.demogracia.com
    -- Mi web de humor al baño María: http://www.demogracia.com
    --
  • Laser Lips

    #2
    Re: Limit &lt;textarea&gt ; length without losing caret position

    TRY...

    <script type="text/javascript">
    function cutLength(e,el, max)
    {
    if(el.value.len gth>max)
    {
    return false;
    }else{
    return true;
    }
    }
    </script>
    <form>
    <input type="text" onkeypress="ret urn cutLength(event ,this,10)" /--
    limit to 10 characters<br/>

    <textarea onkeypress="ret urn cutLength(event ,this,100)"></textarea--
    limit to 100 characters<br/>
    </form>


    ....How ever, this wont stop people cutting and pasting in over the
    limit, it will only stop people when typing normally.

    Graham

    Comment

    • =?ISO-8859-1?Q?=22=C1lvaro_G=2E_Vicario=22?=

      #3
      Re: Limit &lt;textarea&gt ; length without losing caret position

      Laser Lips escribió:
      <script type="text/javascript">
      function cutLength(e,el, max)
      {
      if(el.value.len gth>max)
      {
      return false;
      }else{
      return true;
      }
      }
      [...]
      <textarea onkeypress="ret urn cutLength(event ,this,100)"></textarea--
      [...]
      ...How ever, this wont stop people cutting and pasting in over the
      limit, it will only stop people when typing normally.
      It's an idea but it needs quite polishing: in Firefox, once you hit the
      limit you can't use the arrow keys or delete with keyboard. And the
      clipboard issue would be a problem :( Anyway, thanks for the hint.

      I can think of two approaches:

      1. Listening to textarea events: if an event will result in value being
      changed, then cancel the event.

      2. Good old "if value too large then cut value" with caret position
      handling: save position, cut text and restore position.

      Both look like a lot of work.. *gasp*


      --
      -- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
      -- Mi sitio sobre programación web: http://bits.demogracia.com
      -- Mi web de humor al baño María: http://www.demogracia.com
      --

      Comment

      • Tom Cole

        #4
        Re: Limit &lt;textarea&gt ; length without losing caret position

        On May 9, 8:57 am, "Álvaro G. Vicario"
        <alvaroNOSPAMTH A...@demogracia .comwrote:
        Laser Lips escribió:
        >
        <script type="text/javascript">
        function cutLength(e,el, max)
        {
           if(el.value.len gth>max)
           {
                   return false;
           }else{
                   return true;
           }
        }
        [...]
        <textarea onkeypress="ret urn cutLength(event ,this,100)"></textarea--
        [...]
        ...How ever, this wont stop people cutting and pasting in over the
        limit, it will only stop people when typing normally.
        >
        It's an idea but it needs quite polishing: in Firefox, once you hit the
        limit you can't use the arrow keys or delete with keyboard. And the
        clipboard issue would be a problem :( Anyway, thanks for the hint.
        >
        I can think of two approaches:
        >
        1. Listening to textarea events: if an event will result in value being
        changed, then cancel the event.
        >
        2. Good old "if value too large then cut value" with caret position
        handling: save position, cut text and restore position.
        >
        Both look like a lot of work.. *gasp*
        >
        --
        --http://alvaro.es- Álvaro G. Vicario - Burgos, Spain
        -- Mi sitio sobre programación web:http://bits.demogracia.com
        -- Mi web de humor al baño María:http://www.demogracia.com
        --
        This doesn't work?

        <script type="text/javascript">
        function getCaretPositio n (ctrl) {
        var caretPos = 0;
        if (document.selec tion) {
        ctrl.focus ();
        var Sel = document.select ion.createRange ();
        Sel.moveStart ('character', -ctrl.value.leng th);
        caretPos = Sel.text.length ;
        }
        else if (ctrl.selection Start || ctrl.selectionS tart == '0') {
        caretPos = ctrl.selectionS tart;
        }
        return caretPos;
        }


        function setCaretPositio n(ctrl, pos) {
        if(ctrl.setSele ctionRange) {
        ctrl.focus();
        ctrl.setSelecti onRange(pos,pos );
        }
        else if (ctrl.createTex tRange) {
        var range = ctrl.createText Range();
        range.collapse( true);
        range.moveEnd(' character', pos);
        range.moveStart ('character', pos);
        range.select();
        }
        }

        function checkMax(elemen t, max) {
        var caretpos = getCaretPositio n(element);
        var value = element.value;
        if (value.length max) {
        value = value.substring (0, max);
        }
        element.value = value;
        setCaretPositio n(element, caretpos);
        }
        </script>
        ...
        <textarea cols="5" rows="50" onkeyup="checkM ax(this, 25);"></textarea>

        Comment

        • Dr J R Stockton

          #5
          Re: Limit &lt;textarea&gt ; length without losing caret position

          In comp.lang.javas cript message <7c50f285-c43f-4f29-9d36-b4bb5ae7a922@f3
          6g2000hsa.googl egroups.com>, Fri, 9 May 2008 05:07:21, Laser Lips
          <loudsphiers@gm ail.composted:

          The advice of anyone who posts this code
          >function cutLength(e,el, max)
          >{
          if(el.value.len gth>max)
          {
          return false;
          }else{
          return true;
          }
          >}
          rather than

          function cutLength(e, el, max) { return el.value.length <= max }

          is unlikely to be worth considering.

          --
          (c) John Stockton, nr London UK. ???@merlyn.demo n.co.uk Turnpike v6.05 MIME.
          Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.
          Check boilerplate spelling -- error is a public sign of incompetence.
          Never fully trust an article from a poster who gives no full real name.

          Comment

          • =?ISO-8859-1?Q?=22=C1lvaro_G=2E_Vicario=22?=

            #6
            Re: Limit &lt;textarea&gt ; length without losing caret position

            Tom Cole escribió:
            This doesn't work?
            >
            <script type="text/javascript">
            function getCaretPositio n (ctrl) {
            var caretPos = 0;
            [...]

            It works badly in IE 6. However, it contains some good ideas. If I can't
            find a prewritten script and I have to write mine, I'll take them into
            account.


            --
            -- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
            -- Mi sitio sobre programación web: http://bits.demogracia.com
            -- Mi web de humor al baño María: http://www.demogracia.com
            --

            Comment

            • pradeep

              #7
              Re: Limit &lt;textarea&gt ; length without losing caret position

              On May 13, 3:51 pm, "Álvaro G. Vicario"
              <alvaroNOSPAMTH A...@demogracia .comwrote:
              Tom Cole escribió:This doesn't work?
              >
              <script type="text/javascript">
              function getCaretPositio n (ctrl) {
              var caretPos = 0;
              >
              [...]
              >
              It works badly in IE 6. However, it contains some good ideas. If I can't
              find a prewritten script and I have to write mine, I'll take them into
              account.
              >
              --
              --http://alvaro.es- Álvaro G. Vicario - Burgos, Spain
              -- Mi sitio sobre programación web:http://bits.demogracia.com
              -- Mi web de humor al baño María:http://www.demogracia.com
              --
              <script>
              function textLimit(field , maxlen)
              {
              if (field.value.le ngth maxlen)
              {
              field.value = field.value.sub string(0, maxlen); // if the length
              is more than the limit (maxlen) then take only the first 'maxlen' no.
              of characters
              }
              return (maxlen - field.value.len gth); // current value length is
              returned back
              }
              </script>

              <textarea onkeyup='textLi mit(this,100);r eturn false'></textarea>

              Comment

              • Thomas 'PointedEars' Lahn

                #8
                Re: Limit &lt;textarea&gt ; length without losing caret position

                pradeep wrote:
                <script>
                <script type="text/javascript">
                function textLimit(field , maxlen)
                {
                if (field.value.le ngth maxlen)
                {
                field.value = field.value.sub string(0, maxlen); // if the length
                is more than the limit (maxlen) then take only the first 'maxlen' no.
                of characters
                }
                return (maxlen - field.value.len gth); // current value length is
                returned back
                }
                </script>
                >
                <textarea onkeyup='textLi mit(this,100);r eturn false'></textarea>
                | but all my Google searches either lead to obsolete scripts that
                | overwrite the "value" property (thus losing caret position)


                PointedEars
                --
                realism: HTML 4.01 Strict
                evangelism: XHTML 1.0 Strict
                madness: XHTML 1.1 as application/xhtml+xml
                -- Bjoern Hoehrmann

                Comment

                Working...