Results 1 to 3 of 3

Thread: Javascript Error

  1. #1
    Join Date
    Jun 2008
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Javascript Error

    Hello

    On my webpage I have an input box named "quantity".
    If the user enters nothing or a non-numeric value, an error box is displayed
    and the user is not forwarded to another web page.

    My code is partly working. It checks for the above conditions and displays the proper error message, but still wants to re-direct the page even if the value of the quantity field is not correct.

    Below is my code. Can anyone let me now what I've done wrong?

    Code:
      function CheckQuantity(inp) 
       {     
    	var sValidChars = "0123456789";
    	var sChar       = "";
    	var iCount      = 0;
    	var bIsValid    = true;
            var sTempValue  = inp.value;
    
            if (sTempValue.length == 0) 
            {
    	    alert ("Please enter a valid quantity.");
    	    bIsValid = false;
    	    return bIsValid;
             }
    
            if (sTempValue.length > 0)
            {
    	   for (iCount=0; iCount < sTempValue.length && bIsValid == true; iCount++)
    	   {
    		sChar = sTempValue.charAt(iCount);
    		
    		if (sValidChars.indexOf(sChar) == -1)
    		{
    	    	    alert ("Please enter a numeric value for quantity.");
    		    bIsValid = false;
    		    return bIsValid;
    		}
    	   }
            }
       }
    Last edited by jscheuer1; 01-19-2009 at 05:12 AM. Reason: format code

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Your code looks OK, though a bit more complex than is needed. Basically what you are doing is returning true if the value passes certain tests, and alerting a message while returning false if it does not.

    All well and good. But the crucial part is what does your form do with the return value? Part of this would be a result of where this function is called. Pretty much the ideal place would be onsubmit of the form, ex:

    Code:
    <form action="whatever" onsubmit="return CheckQuantity(this.elements.name_of_the_input);">
    
    form contents
    
    </form>
    If you want more help we would need to see the form. Better yet:

    Please post a link to the page on your site that contains the problematic code so we can check it out.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Yes, your code is largely redundant: the following performs the same function:
    Code:
    function checkQuantity(inp) {
        if (!inp.value)
            return !!alert("Please enter a valid quantity.");
        else if (!/^\d$/.test(inp.value))
            return !!alert("Please enter a numeric value for quantity.");
        else
            return true;
    }
    Or even, arguably at the loss of a little readability:
    Code:
    function checkQuantity(inp) {
      return !!(   (inp.value              || alert("Please enter a valid quantity."))
                && (/^\d$/.test(inp.value) || alert("Please enter a numeric value for quantity.")));
    }
    Note the conventions, not universal but widely followed by those aware of their existence: formatting is Java-style (braces on the same line), with a space before the brackets of keywords but not of functions; capitals are reserved for namespaces and constructor functions.

    There are three reasons that the return value of a function will not map directly to a processed/non-processed event:
    1. The return value was not used as the return value of the event handler, as John showed you above; if you're assigning the handler from script, this maps to a function like:
      Code:
      myForm.onsubmit = function() {
        return checkQuantity(this.elements.name_of_the_input);
      };
    2. You were using DOM-2 or Microsoft events instead of assigning the function directly in script or code: these systems have their own methods of cancelling an event's propagation, namely event.cancelBubble = true in Microsoft or event.stopPropagation() in DOM-2.
    3. An error occurred somewhere in your code: if an error is thrown in the event handler, processing will stop and its return value will be ignored (considered true). If this is the case, wrap your event handler in a try block (try { return eventHandler(); } catch (e) { return false; }) to aid debugging, and check your error console.
    Last edited by Twey; 01-19-2009 at 11:46 AM.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •