Announcement

Collapse
No announcement yet.

Javascript Faq

Collapse
This is a sticky topic.
X
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Javascript Faq

    To format a number to a fixed number of decimal places, use:
    Code:
    function formatNumber(expr, decimals) {
             var str = "" + Math.round( eval(expr) * Math.pow(10,decimals))
             while (str.length <= decimals) { str = "0" + str } 
             var decpoint = str.length - decimals; 
             var result = str.substring(0,decpoint);
             if (decimals) result += "." + str.substring(decpoint,str.length);
             return result;
    }
    var someNumber = 786/7
    var sixPlaces = (someNumber,6)
    var noDecimals = formatNumber(someNumber)
    var pi4 = formatNumber(355/113,4)
    Jon Hanlon

  • #2
    HTML/ Javascript Faq

    Q. How do I set the focus to elements on the page?

    A. By using an event handler coupled with JavaScript.

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
    	<title>Untitled</title>
    </head>
    <body>
    <form>
    <input type=button value="Focus On Link" onClick="document.links[0].focus()"> 
    <input type=button value="Focus On Text Field" onClick="document.forms[0].text1.focus()"> 
    <input type=button value="Focus On Select Box" onClick="document.forms[0].select1.focus()"> 
    <input type=button value="Focus On Radio Button" onClick="document.forms[0].radio1.focus()"> 
    <input type=button value="Focus On a Button" onClick="document.forms[0].button1.focus()"> 
    <br><br><br>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="blah">here</a>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type=text name=text1>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select name=select1>
    <option selected>Choose One...</option>
    <option>Option1</option>
    <option>Option2</option>
    </select>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type=radio name=radio1>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type=button value="Sample Button" name=button1>
    </form>
    </body>
    </html>
    Attached Files

    Comment


    • #3
      JavaScript Faq

      Q. How do I verify that a email address is entered correctly?

      A. Use JavaScript to inspect the entry. The following code only returns a alert if the email address is not valid.
      Code:
      <html>
      <head>
      <script language="JavaScript">
      <!--
      
      // -----------------------------------------------------------------
      // Function    : IsEmailValid
      // Language    : JavaScript
      // Description : Checks if given email address is of valid syntax
      // Copyright   : (c) 1998 Shawn Dorman
      // http://www.goodnet.com/~sdorman/web/IsEmailValid.html
      // -----------------------------------------------------------------
      // Ver    Date    Description of modification
      // --- ---------- --------------------------------------------------
      // 1.0 09/04/1996 Original write
      // 1.1 09/30/1998 CHG: Use standard header format
      // -----------------------------------------------------------------
      // Source: Webmonkey Code Library
      // (http://www.hotwired.com/webmonkey/ja.../code_library/)
      // -----------------------------------------------------------------
      
      function IsEmailValid()
      {
      var EmailOk  = true
      var Temp     = document.form1.email
      var AtSym    = Temp.value.indexOf('@')
      var Period   = Temp.value.lastIndexOf('.')
      var Space    = Temp.value.indexOf(' ')
      var Length   = Temp.value.length - 1   // Array is from 0 to length-1
      
      if ((AtSym < 1) ||                     // '@' cannot be in first position
          (Period <= AtSym+1) ||             // Must be atleast one valid char btwn '@' and '.'
          (Period == Length ) ||             // Must be atleast one valid char after '.'
          (Space  != -1))                    // No empty spaces permitted
         {  
            EmailOk = false
            alert('Please enter a valid e-mail address!')
            Temp.focus()
         }
      return EmailOk
      }
      // -->
      </script>
      </head>
      <body>
      <form name=form1>
      <br>
      <input type=text name=email size=15>
      &nbsp;&nbsp;&nbsp;
      <input type=button onClick="IsEmailValid()" value="verify email address">
      </form>
      </body>
      </html>
      Attached Files

      Comment


      • #4
        JavaScript Faq

        Q. How do I automatically round nunmbers that the user enters?

        A. With a handy bit of JavaScript.

        Code:
        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
        <html>
        <head>
        	<title>Untitled</title>
        <script language=javascript>
        function roundAmount(amount, where)
        {
          var s = "";
          var decimal;
          amount = parseFloat(amount);
          if (!(isNaN(amount))) {
            // round to nearest cent
            amount = Math.round(amount * 100);
            amount = amount / 100;
        
            // format the output
            s = new String(amount);
            decimal = s.indexOf(".");
            if (decimal == -1) {
              // whole number
              s+= ".00";
            } else {
              if (decimal == (s.length - 2)) {
                // needs a trailing zero
                s+= "0";
              }
            }
          } else {
            // not a number so return zero
            s = "0.00";
          }  
          where.value=s;
          return s;
        }
        </script>
        </head>
        
        <body>
        <form>
        <input type=text name=numbers onBlur="roundAmount(this.value, this)">
        <input type=button value="Click Me!">
        </form>
        </body>
        </html>
        Attached Files

        Comment


        • #5
          JavaScript Faq

          Q. How do I limit the characters in a textarea?

          A. Use a little JavaScript, and all will be well!

          Code:
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
          <html>
          <head>
          	<title>Untitled</title>
          <SCRIPT LANGUAGE="JavaScript">
          <!-- Original:  Ronnie T. Moore -->
          <!-- Web Site:  The JavaScript Source -->
          
          <!-- Dynamic 'fix' by: Nannette Thacker -->
          <!-- Web Site: http://www.shiningstar.net -->
          
          <!-- This script and many more are available free online at -->
          <!-- The JavaScript Source!! http://javascript.internet.com -->
          
          <!-- Begin
          function textCounter(field, countfield, maxlimit) {
          if (field.value.length > maxlimit) // if too long...trim it!
          field.value = field.value.substring(0, maxlimit);
          // otherwise, update 'characters left' counter
          else 
          countfield.value = maxlimit - field.value.length;
          }
          // End -->
          </script>
          </head>
          <body>
          <form name=form1>
          <textarea name=content cols=70 rows=18 onKeyDown="textCounter(this.form.content,this.form.remLen,4000);" 
          onKeyUp="textCounter(this.form.content,this.form.remLen,4000);" 
          onFocus="textCounter(this.form.content,this.form.remLen,4000);">
          </textarea>
          <br><br>
          <input readonly type=text name=remLen size=2 maxlength=3 value="4000" style="border: 1px;">&nbsp;characters left</font>
          </form>
          </body>
          </html>
          Attached Files

          Comment


          • #6
            Javascript keywords

            When scripting Javascript, do not use a keyword as an identifier.
            Current and reserved future keywords are:
            Code:
            abstract     else            instanceof    switch           
            boolean      enum            int           synchronized    
            break        export          interface     this            
            byte         extends         long          throw           
            case         false           native        throws          
            catch        final           new           transient       
            char         finally         null          true            
            class        float           package       try             
            const        for             private       typeof          
            continue     function        protected     var             
            debugger     goto            public        void            
            default      if              return        volatile        
            delete       implements      short         while           
            do           import          static        with            
            double       in              super
            When naming identifiers it is also important to avoid any words that are
            already the names of intrinsic Javascript objects, properties, methods
            or functions, such as Date, PI, test or escape.
            Jon Hanlon

            Comment


            • #7
              Javascript Window settings

              You cannot change the Chrome of the current window. You can open a new window and specify the Chrome (status bar, location field, menubar, toolbar etc.), but you cannot change the current window's settings.
              The reasoning behind this is to stop rogue sites from hiding the back button, location field etc. thus making it difficult for users to leave the site.
              Jon Hanlon

              Comment


              • #8
                Internet Explorer

                For IE5+, you can set the homepage by doing:
                Code:
                <a href="javascript:void(0)"
                 onclick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.yourSite.com');">
                Make us your Homepage
                </a>
                Note that the user must confirm that this is OK.
                Jon Hanlon

                Comment


                • #9
                  Javascript FAQ

                  Q: How do I block javascript errors?
                  A: Insert the following code between your <head> tags:

                  Code:
                  <head>
                  <script type="text/javascript" language="javascript">
                  window.onerror = function(){return true;} 
                  </script>
                  </head>

                  Comment


                  • #10
                    Maintaining State

                    HTML is a stateless
                    protocol, which means that it has the memory of a goldfish. Every page is
                    unaware of what happened previously, and it is difficult to pass variables
                    from one page to the next. There are three non-server related methods
                    for maintaining state:
                    • Cookies
                    • Frames
                    • URL Search property

                    Cookies
                    Can be set and then read by the next page. There are heaps of Cookie How To's
                    around. Most functions are based on Bill Dortch's public domain functions.
                    eg. See http://www.webdeveloper.com/javascri...t_cookies.html
                    The disadvantage of cookies is that they can be turned off by the user.

                    Frames
                    The topmost window or a static banner frame can be used to store variables
                    whilst other frames change. Useful is the special keyword top which
                    refers to the page containing the first frameset.
                    eg. top.favoriteFood = "Ice Cream" , parent.frames.banner.myName="Lee"
                    The disadvantage is that frames may be impractical.

                    URL Search property
                    The location object includes protocol, host, pathname, hash and search, so
                    we can load up the search property to suit our needs.
                    The disadvantage is that the user can see (and possibly alter) the data, so
                    if you're passing anything important it's best to encrypt it with several
                    check digits.

                    An example illustrates:

                    Page 1
                    Code:
                      <form>
                        <input type="button" onclick="nextPage('Disney')" value="Disney Ducks">
                        <input type="button" onclick="nextPage('Warner')" value="Warner Ducks">
                      </form>
                    
                      <script language="Javascript">
                       function nextPage(strStudio) {
                          var strSearch = "?studio=" + strStudio; 
                          if (strStudio == "Warner") strSearch += "&ducks=Daffy";
                          if (strStudio == "Disney") strSearch += "&ducks=Huey+%2C+Duey+%26+Looey";
                          var newLocation = "http://www.someSite.com/Page2.html" + strSearch
                    
                          location.assign(newLocation)
                       }
                       </script>
                    This page simply navigates to the next page using either
                    http://www.someSite.com/Page2.html?s...Duey+%26+Looey
                    or
                    http://www.someSite.com/Page2.html?s...er&ducks=Daffy

                    Note that we replace spaces by plus(+) signs, and punctuation by the ascii code
                    (comma = %2C Ampersand = %26).

                    The next page needs to examine the search property of the URL:
                    Page 2
                    Code:
                    <script language="Javascript">
                    function plusUnescape(str) { // the unescape function won't convert plus signs
                             str = '' + str;     // to spaces; like you see in search strings
                             while (true) {
                                   var j = str.indexOf('+');
                                   if (j == -1) break;
                                   str = str.substring(0,j) + ' ' + str.substring(j+1,str.length);
                             }
                             return unescape(str);
                    }
                    
                    function getArgument (theKey) {
                             var args = new Array ();
                             var argstring = window.location.search;
                             if (argstring.charAt(0) != '?') return false;
                             argstring = argstring.substring(1, argstring.length);
                             var argarray = argstring.split('&');
                             for (var j=0; j < argarray.length; j++) {
                             var singlearg = argarray[j].split('=');
                                 if (singlearg.length != 2) continue; // not a valid argument
                                 var argsKey    = plusUnescape(singlearg[0]);
                                 var argsValue  = plusUnescape(singlearg[1]);
                                 args [argsKey] = argsValue;
                             }
                             return args[('' + theKey)]
                    }
                    
                    function whichDucks() {
                             var strStudio = getArgument("studio")
                             if (!strStudio) return false; // nothing passed
                             var strDucks = getArgument("ducks")
                             alert("The " + strStudio + " studio created the duck(s) " + strDucks)
                    }
                    </script>
                    
                      <form>
                        <input type="button" onclick="whichDucks()" value="Which Ducks">
                      </form>
                    Jon Hanlon

                    Comment


                    • #11
                      Originally posted by Dr. Web
                      JavaScript Faq

                      Q. How do I limit the characters in a textarea?

                      A. Use a little JavaScript, and all will be well!


                      Code:
                      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
                      <html>
                      <head>
                      	<title>Untitled</title>
                      <SCRIPT LANGUAGE="JavaScript">
                      <!-- Original:  Ronnie T. Moore -->
                      <!-- Web Site:  The JavaScript Source -->
                      
                      <!-- Dynamic 'fix' by: Nannette Thacker -->
                      <!-- Web Site: http://www.shiningstar.net -->
                      
                      <!-- This script and many more are available free online at -->
                      <!-- The JavaScript Source!! http://javascript.internet.com -->
                      
                      <!-- Begin
                      function textCounter(field, countfield, maxlimit) {
                      if (field.value.length > maxlimit) // if too long...trim it!
                      field.value = field.value.substring(0, maxlimit);
                      // otherwise, update 'characters left' counter
                      else 
                      countfield.value = maxlimit - field.value.length;
                      }
                      // End -->
                      </script>
                      </head>
                      <body>
                      <form name=form1>
                      <textarea name=content cols=70 rows=18 onKeyDown="textCounter(this.form.content,this.form.remLen,4000);" 
                      onKeyUp="textCounter(this.form.content,this.form.remLen,4000);" 
                      onFocus="textCounter(this.form.content,this.form.remLen,4000);">
                      </textarea>
                      <br><br>
                      <input readonly type=text name=remLen size=2 maxlength=3 value="4000" style="border: 1px;">&nbsp;characters left</font>
                      </form>
                      </body>
                      </html>
                      Found a NS 7.02 bug on this one. It shows 400 chars left instead of 4000, and deducts 1 char every 10 chars (so maybe it is a display problem since it will still stop you at 4000 chars even with the bug)?
                      Web Templates and Graphic Templates
                      Stock Photos
                      CMS Skins
                      Turnkey Websites

                      Comment


                      • #12
                        here Jason, just replace this with what you got.
                        Code:
                        <SCRIPT LANGUAGE="JavaScript">
                        <!-- Original:  Ronnie T. Moore -->
                        <!-- Web Site:  The JavaScript Source -->
                        
                        <!-- Dynamic 'fix' by: Nannette Thacker -->
                        <!-- Web Site: http://www.shiningstar.net -->
                        
                        <!-- This script and many more are available free online at -->
                        <!-- The JavaScript Source!! http://javascript.internet.com -->
                        
                        <!-- Begin
                        function textCounter(field, countfield, maxlimit) {
                        if (field.value.length > maxlimit) // if too long...trim it!
                        field.value = field.value.substring(0, maxlimit);
                        // otherwise, update 'characters left' counter
                        else
                        countfield.value = maxlimit - field.value.length;
                        }
                        // End -->
                        </script>
                        code in html
                        Code:
                        Maximum Number of characters for this text box is 250.<br>
                        <TEXTAREA onKeyDown="textCounter(this.form.CustomVerseText,this.form.remLen,250);"
                        onKeyUp="textCounter(this.form.CustomVerseText,this.form.remLen,250);"
                        onFocus="textCounter(this.form.CustomVerseText,this.form.remLen,250);"
                        name=CustomVerseText rows=7 wrap=physical cols=60 maxLength="250"></TEXTAREA>
                        <br><br>
                        
                        You have <B><input type="text" readonly name=remLen size=2 maxlength=3 value="250" style="border: 1px;"></B>characters remaining
                        for your description...</font>
                        I have it set to 250 and it worked in Mozilla so it should work in all of them.
                        Have a Script or Snippet you want to share?

                        WWW Standards: HTML 4.01,
                        HTML 5, CSS2.1, CSS3, XHTML 1.0
                        PHP Standards: PHP Standards

                        Comment


                        • #13
                          Originally posted by Dr. Web View Post
                          JavaScript Faq

                          Q. How do I limit the characters in a textarea?

                          A. Use a little JavaScript, and all will be well!

                          Code:
                          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
                          <html>
                          <head>
                          	<title>Untitled</title>
                          <SCRIPT LANGUAGE="JavaScript">
                          <!-- Original:  Ronnie T. Moore -->
                          <!-- Web Site:  The JavaScript Source -->
                          
                          <!-- Dynamic 'fix' by: Nannette Thacker -->
                          <!-- Web Site: http://www.shiningstar.net -->
                          
                          <!-- This script and many more are available free online at -->
                          <!-- The JavaScript Source!! http://javascript.internet.com -->
                          
                          <!-- Begin
                          function textCounter(field, countfield, maxlimit) {
                          if (field.value.length > maxlimit) // if too long...trim it!
                          field.value = field.value.substring(0, maxlimit);
                          // otherwise, update 'characters left' counter
                          else 
                          countfield.value = maxlimit - field.value.length;
                          }
                          // End -->
                          </script>
                          </head>
                          <body>
                          <form name=form1>
                          <textarea name=content cols=70 rows=18 onKeyDown="textCounter(this.form.content,this.form.remLen,4000);" 
                          onKeyUp="textCounter(this.form.content,this.form.remLen,4000);" 
                          onFocus="textCounter(this.form.content,this.form.remLen,4000);">
                          </textarea>
                          <br><br>
                          <input readonly type=text name=remLen size=2 maxlength=3 value="4000" style="border: 1px;">&nbsp;characters left</font>
                          </form>
                          </body>
                          </html>

                          Or you could just use RegExp? Noticing this is 8 years old I won't doubt it, though

                          Comment

                          Working...
                          X