3 Replies Latest reply on Dec 23, 2016 2:05 AM by Vamitul

    edit text maximum length

    hamdifem Level 1

      Do not write more than 8 characters

      How to limit character

       

       

      var w= new Window ("Section");

      var prefix = w.add("edittext", undefined, "")

       

      prefix.onChanging = function () {

      if(prefix.text.length >=9){

          prefix.text.substring(0,9); //???

          }

      }

        • 2. Re: edit text maximum length
          [Jongware] Most Valuable Participant

          Please don't suggest code that does not work correctly to begin with! The first argument of "Window" must be "dialog", "window", or "palette".

          You have (or should have) enough scripting experience to be able to see that your line is only half correct. You take a substring from something ... and then what? You throw it away!

           

          This fixes your immediate problem:

          prefix.onChanging = function () {
          if(prefix.text.length > 8){
              prefix.text = prefix.text.substring(0,8);
              }
          }
          

           

          But -- as stated in several other posts that use onChanging -- it's very annoying that the cursor position gets reset. I found this post very illuminating: Edittext and onChanging event  and so I came up with the following.

           

          var w= new Window ("dialog","Section");
          var prefix = w.add("edittext", undefined, "")
          prefix.characters = 8;
          prefix.addEventListener ('keydown', rejectTooLong ); 
          w.show();
          
          function rejectTooLong (event)
          {
            var obj = event.currentTarget;
            if (obj.text.length >= obj.characters)
            {
            if ({"Backspace":1,"Escape":1,"Return":1}[event.keyName]==null)
            {
              event.stopPropagation();
            event.preventDefault();
           }
            }
          }
          
          • 3. Re: edit text maximum length
            Vamitul Level 4

            You are close enough.

            Just need to remember that in JS strings are immutable, so string.substring returns a new string, does not change the original one.

            so..

            prefix.text=prefix.text.substring(0,9); //???

            1 person found this helpful