JavaScript

David Flanagan

Mentioned 17

A revised and updated edition offers comprehensive coverage of ECMAScript 5 (the new JavaScript language standard) and also the new APIs introduced in HTML5, with chapters on functions and classes completely rewritten and updated to match current best practices and a new chapter on language extensions and subsets. Original.

More on Amazon.com

Mentioned in questions and answers.

It should be a combination of CSS and Javascript,

The main jobs to do should be:

  1. Make it on top of all other elements (which property to specity?)
  2. Catch the event it is clicked (which event to listen to?)
  3. Move the div as mouse moves.

but what are the details?

  1. make it absolute positioned, with a high z-index.
  2. check for onmousedown of the div.
  3. use the event's mouseX and mouseY attributes to move the div.

Here's an example from Javascript, the Definitive Guide (updated here):

/**
 *  Drag.js:    drag absolutely positioned HTML elements.
 *
 *  This module defines a single drag() function that is designed to be called
 *  from an onmousedown event handler. Subsequent mousemove event will
 *  move the specified element. A mouseup event will terminate the drag.
 *  If the element is dragged off the screen, the window does not scroll.
 *  This implementation works with both the DOM Level 2 event model and the
 *  IE event model.
 *
 *  Arguments:
 *
 *      elementToDrag: the element that received the mousedown event or
 *          some containing element. It must be absolutely positioned. Its
 *          style.left and style.top values will be changed based on the user's
 *          drag.
 *
 *      event: ethe Event object for the mousedown event.
 *
 *  Example of how this can be used:
 *      <script src="Drag.js"></script> <!-- Include the Drag.js script -->
 *      <!-- Define the element to be dragged -->
 *      <div style="postion:absolute; left:100px; top:100px; width:250px;
 *                  background-color: white; border: solid black;">
 *      <!-- Define the "handler" to drag it with. Note the onmousedown attribute. -->
 *      <div style="background-color: gray; border-bottom: dotted black;
 *                  padding: 3px; font-family: sans-serif; font-weight: bold;"
 *          onmousedown="drag(this.parentNode, event);">
 *      Drag Me <!-- The content of the "titlebar" -->
 *      </div>
 *      <!-- Content of the draggable element -->
 *      <p>This is a test. Testing, testing, testing.<p>This is a test.<p>Test.
 *      </div>
 *
 *  Author: David Flanagan; Javascript: The Definitive Guide (O'Reilly)
 *  Page: 422
 **/
 function drag(elementToDrag, event)
 {
     // The mouse position (in window coordinates)
     // at which the drag begins
     var startX = event.clientX, startY = event.clientY;

     // The original position (in document coordinates) of the
     // element that is going to be dragged. Since elementToDrag is
     // absolutely positioned, we assume that its offsetParent is the
     //document bodt.
     var origX = elementToDrag.offsetLeft , origY = elementToDrag.offsetTop;

     // Even though the coordinates are computed in different
     // coordinate systems, we can still compute the difference between them
     // and use it in the moveHandler() function. This works because
     // the scrollbar positoin never changes during the drag.
     var deltaX = startX - origX, deltaY = startY - origY;

     // Register the event handlers that will respond to the mousemove events
     // and the mouseup event that follow this mousedown event.
     if (document.addEventListener) //DOM Level 2 event model
     {
         // Register capturing event handlers
         document.addEventListener("mousemove", moveHandler, true);
         document.addEventListener("mouseup", upHandler, true);
     }
     else if (document.attachEvent) //IE 5+ Event Model
     {
         //In the IE event model, we capture events by calling
         //setCapture() on the element to capture them.
         elementToDrag.setCapture();
         elementToDrag.attachEvent("onmousemove", moveHandler);
         elementToDrag.attachEvent("onmouseup", upHandler);
         // Treat loss of mouse capture as a mouseup event.
         elementToDrag.attachEvent("onclosecapture", upHandler);
     }
     else //IE 4 Event Model
     {
         // In IE 4, we can't use attachEvent() or setCapture(), so we set
         // event handlers directly on the document object and hope that the
         // mouse event we need will bubble up.
         var oldmovehandler = document.onmousemove; //used by upHandler()
         var olduphandler = document.onmouseup;
         document.onmousemove = moveHandler;
         document.onmouseup = upHandler;
     }

     // We've handled this event. Don't let anybody else see it.
     if (event.stopPropagation) event.stopPropagation();    //  DOM Level 2
     else event.cancelBubble = true;                        //  IE

     // Now prevent any default action.
     if (event.preventDefault) event.preventDefault();      //  DOM Level 2
     else event.returnValue = false;                        //  IE

     /**
      * This is the handler that captures mousemove events when an element
      * is being dragged. It is responsible for moving the element.
      **/
      function moveHandler(e)
      {
          if (!e) e = window.event; //  IE Event Model

          // Move the element to the current mouse position, adjusted as
          // necessary by the offset of the initial mouse-click.
          elementToDrag.style.left = (e.clientX - deltaX) + "px";
          elementToDrag.style.top = (e.clientY - deltaY) + "px";

          // And don't let anyone else see this event.
          if (e.stopPropagation) e.stopPropagation();       // DOM Level 2
          else e.cancelBubble = true;                       // IE
      }

      /**
       * This is the handler that captures the final mouseup event that
       * occurs at the end of a drag.
       **/
       function upHandler(e)
       {
           if (!e) e = window.event;    //IE Event Model

           // Unregister the capturing event handlers.
           if (document.removeEventListener) // DOM event model
            {
                document.removeEventListener("mouseup", upHandler, true);
                document.removeEventListener("mousemove", moveHandler, true);
            }
            else if (document.detachEvent)  //  IE 5+ Event Model
            {
                elementToDrag.detachEvent("onlosecapture", upHandler);
                elementToDrag.detachEvent("onmouseup", upHandler);
                elementToDrag.detachEvent("onmousemove", moveHandler);
                elementToDrag.releaseCapture();
            }
            else    //IE 4 Event Model
            {
                //Restore the original handlers, if any
                document.onmouseup = olduphandler;
                document.onmousemove = oldmovehandler;
            }

            //  And don't let the event propagate any further.
            if (e.stopPropagation) e.stopPropagation(); //DOM Level 2
            else e.cancelBubble = true;                 //IE
       }
 }

 function closeMe(elementToClose)
 {
     elementToClose.innerHTML = '';
     elementToClose.style.display = 'none';
 }

 function minimizeMe(elementToMin, maxElement)
 {
     elementToMin.style.display = 'none';
 }

Similar to, but different from this question. The code below is from JavaScript: The Definitive Guide. He's basically defining an inherit method that defers to Object.create if it exists, otherwise doing plain old Javascript inheritance using constructors and swapping prototypes around.

My question is, since Object.create doesn't exist on plenty of common browsers IE, what's the point of even trying to use it? It certainly clutters up the code, and one of the commenters on the previous question mentioned that Object.create isn't too fast.

So what's the advantage in trying to add extra code in order to occasionally utilize this ECMA 5 function that may or may not be slower than the "old" way of doing this?

function inherit(p) {
   if (Object.create) // If Object.create() is defined...
      return Object.create(p); // then just use it.

   function f() {}; // Define a dummy constructor function.
   f.prototype = p; // Set its prototype property to p.
   return new f(); // Use f() to create an "heir" of p.
}

The speed difference is not very noticeable, since by nature you probably won't be creating too many objects (hundreds, even thousands isn't what I call a lot), and if you are and speed is a critical issue you probably won't be coding in JS, and if both of the above aren't true, then I'm sure within a few releases of all popular JS engines the difference will be negligible (this is already the case in some).

In answer to your question, the reasons aren't speed-related, but because the design pattern of Object.create is favoured to the old method (for the reasons outlined in that and other answers). They allow for proper utilisation of the ES5 property attributes (which make for more scalable objects, and thus more scalable apps), and can help with inheritance hierarchies.

It's forward engineering. If we took the line of "well it isn't implemented everywhere so let's not get our feet wet", things would move very slowly. On the contrary, early and ambitious adoption helps the industry move forward, helps business decision makers support new technologies, helps developers improve and perfect new ideas and the supporting frameworks. I'm an advocate for early (but precautionary and still backward-compatible) adoption, because experience shows that waiting for enough people to support a technology can leave you waiting far too long. May IE6 be a lesson to those who think otherwise.

the following lines are from the official jQuery website

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="http://code.jquery.com/jquery-1.4.2.min.js"><\/script>');</script>

I'm not sure about the HTML parse order, or should I say script execution order.

The question is: Will line 2 wait for line 1 to load? I doubt it.

If line 1 is still being loaded (say it's 3000KB, and takes long), and line 2 is executed already. window.jQuery would always be false, and so the second js is always included. If that's true, what is line 1 for anyway?

Lets talk about the more traditional way of handling without using attribute defer or async

The browsers will:

  1. Download scripts, blocking other resource from downloading

  2. Parse the scripts

  3. Execute the scripts

See Ch1, Loading and Executing from High Performance JavaScript

Here's another good reference 12.3. Execution of JavaScript Programs from JavaScript: The Definitive Guide, 4th Edition

I am having trouble understanding the meaning and more importantly the concept of an object as it relates to jQuery. I understand the basics that its a collection of data that comes in two forms, properties and methods but I kind of get lost on how it works beyond that. Can anyone point me to some good tutorials that maybe helped you understand? I'm hoping to "Get it" once and for all.

Many many thanks for your help! =]

Understanding pure JavaScript first would be your first objective and learning how objects are defined there. I recommend the JavaScript: the definitive guide By David Flanagan.

Once understanding the JS model you can start looking under the hood of jQuery and understand what is being done. jQuery just takes advantage of the JavaScript language making an easy to use framework: http://www.learningjquery.com/2008/12/peeling-away-the-jquery-wrapper

Notice the closure example below:

<script>
  function foo() {
    var x = 1;
    function bar() {
      var y = 2;
      alert(x + y);
    }
    return bar;
  }

   var dummy = foo(); // Assign variable binding "dummy" to a reference of the "bar" function.
   dummy(); // When entering the "bar" function code, will it go through the execution context creation phase?
</script>

When invoking the dummy variable binding (which will execute the "bar" function code), is a new execution context created? The ECMAScript Specification specifies what happens when entering function code, but since this is a reference to a function/closure, I wasn't sure if it had to go through the whole execution context creation/binding phase again.

I think scope chain is the thing you are looking here:

From http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/ref=sr_1_2?ie=UTF8&qid=1362066219&sr=8-2&keywords=javascript (3.10.3)

Every time a function is invoked, it creates a new object to store its local variables, and adds that new object to the stored scope chain to create a new, longer, chain that represents the scope for that function invocation.

For your question yes it will again go through the whole execution context, otherwise how can you return another function from bar() like

function bar() {
      var y = 2;
      alert(x + y);

return function() {alert('hello');}
    }

I'm working on a JavaScript syntax highlighter, that I need for a project I'm starting later.

I have an expression called keywords.

var keywords = /break|case|catch|default|delete|do|else|false|for|function|if|in|instanceof|new|null|prototype|return|switch|throw|this|true|try|typeof|var|while|with/g

I then run script.replace(keywords, "<keyword>" + /* I have no idea what to put here. */ + "</keyword>");

How can I tell what it's replacing, so I can insert the keyword in between the tags?

Or you can do this:

var keywords = /break|case|catch|default|delete|do|else|false|for|function|if|in|instanceof|new|null|prototype|return|switch|throw|this|true|try|typeof|var|while|with/g;
var script = 'return 1';
script.replace(keywords, "<keyword>$&</keyword>");

That is, in this simple case, you don't need to use capturing parentheses. The special token: $& returns the text matched by the whole regex. (In other languages, this is frequently specified as: $0 - i.e. capture group zero.) There are several special tokens you can use in a Javascript string.replace string:

    $1, $2, $3,...$99  The text matching capture groups 1-99.
    $&                 The substring that matched the whole regex.
    $`                 The text to the left of the matched substring.
    $'                 The text to the right of the matched substring.
    $$                 A literal dollar sign

This is taken from: "Javascript: the Definitive Guide (5th Edition)", by David Flanagan. This excellent Javascript reference is highly recommended (and there is a new revision about to come out too - Yay!)

And regarding Javascript syntax highlighting... I've been looking into this lately and can make a couple recommendations:
* The most popular is SyntaxHighlighter. However, I recently discovered a nasty bug at its very core and wrote an article about it: Fixing the SyntaxHighlighter 3.0.83 Parser Bug
* Also, take a look at the McLexer/McHighlighter by Matt Might. (This guy is wicked smart). Although this one also has a bug when you run it under Opera. (this bug is easily fixed by removing the line which explicitly compiles the regex.)
* Also, take a look at Google prettify (which is used by this site if I'm not mistaken).

Can any one here suggest a good Dojo and JSON book or a site for tutorials please for a graduate student.

Many Thanks!

I wouldn't really recommend reading a book since you can get very close to the same content online if you know how to look for it, but if you insist, the definitive guide books are always very helpful (you'll need to purchase two off them though to get info about dojo and json):

http://www.amazon.com/Dojo-Definitive-Guide-Matthew-Russell/dp/0596516487

http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/ref=pd_sim_b_1

Javascript: The Definitive Guide will teach you everything you need to know (and more) about JSON, and will prepare you for using frameworks like Dojo, Mootools, jQuery... etc.

I own David Flanagan's Most Excellent "Javascript: The Definitive Guide" and I agree - it's a must-have for any Javascript developer.

... however ...

The one framework Flanagan covers is jQuery (not Javascript).

I'd recommend the on-line IBM Redbooks for Dojo and JSON:

Etc. etc

And, even more than Flanagan ("The Rhino Book"), I'd very strongly recommend Douglas Crockford's "Javascript: The Good Parts" as a must-have for every Javascript developer:

I am about to move to a job where I will be doing front end web development (mainly CSS and jQuery).

What are good resources (books, websites, blogs etc.) for learning more about those technologies in particular and anything front-end web development related (good technologies to know, user interface ideas etc.) in general?

Thank you!

ETA: Just to give some idea of where I'm holding, I have about 1.5 years of experience in web development. So I already have a pretty good grasp of CSS and know the basics of jQuery. I also know a fair amount about user interface design.

i assume you will also be doing HTML since this is at the core of FE dev. HTML, seems simple and is easy to ignore as a technology, but you should not turn your nose up to it. Writing terse, clean and semantic HTML is a skill and requires lots of learning and practice just as CSS and JS.

Right, now onto things you actually requested :)

For jQuery i would definitely consider learning as much as you can about JavaScript proper. Whilst you can write jQuery without knowing all that much about JavaScript, you need to understand JavaScript to make the most of jQuery and write better code. And of course to know when you can get away with using plain ol' JS.

JS resources:

CSS resources:

Good websites to have in your RSS client:

hope that helps in your quest into front-end development!

I am trying to learn JavaScript from JavaScript: The Definitive Guide 6th ed. On page 81, the author explains that there is a difference if you call eval by its original name, as opposed to when you create a different name. The author illustrates with the following source code:

var geval = eval;               // Using another name does a global eval
var x = "global", y = "global"; // Two global variables

function f()  // This function does a local eval
{
    var x = "local";            // Define a local variable
    eval("x += 'changed';");    // Direct eval sets local variable
    return x;                   // Return changed local variable
}

function g()  // This function does a global eval
{
    var y = "local";            // A local variable
    geval("y += 'changed';");   // Indirect eval sets global variable
    return y;                   // Return unchanged local variable
}

console.log(f(), x); // Local variable changed: prints "localchanged global":
console.log(g(), y); // Global variable changed: prints "local globalchanged":

I tried to execute the code and I get:

/usr/bin/node test.js

localchanged global
undefined:1
y += 'changed';
^
ReferenceError: y is not defined
    at eval (eval at g (/home/martin/Projects/WebPages/test.js:18:5), <anonymous>:1:1)
    at eval (native)
    at g (/home/martin/Projects/WebPages/test.js:18:5)
    at Object.<anonymous> (/home/martin/Projects/WebPages/test.js:23:13)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)

Process finished with exit code 8

Please, could you explain, why the y variable is not visible in the call to geval?

I need to know the difference between these three types of variable initialization.

1)- The first type is using the "this" keyword.

var x=function (data1,data2){
this.data1=data1;
this.data2=data2;
}

2)- Second is using the "var" keyword...from what i know the var keyword makes the scope of a variable local which means that var can only be accessible when we are inside the function.

var x=function (data1,data2){
var data1=data1;
var data2=data2;
}

3)- Third type is without using any keyword..from what i know is that we don't specify the var keyword with a variable then it becomes global for the complete application. So you can access it any where you want...but in this case i think this would throw an error...because how would javascript know if data1 is a variable or a parameter (the passed on argument) ?

var x=function (data1,data2){
data1=data1;
data2=data2;
}

1) this.foo = bar

The first kind you mention makes your variables properties of a (constructor) function. In JavaScript, functions are objects. Thus, using this makes a variable a property of an object (your constructor function, in this case).

2) var x = 7

Let me start off saying that anytime you do not use var in front of a variable (save for the this stuff above), that variable will become a member of the global context object (window, for most user-agents).

Thought leaders in JavaScript and programming see global variables as a sin, or code smell. Avoid global variables as much as possible.

The issue with the first method (this) is that prior to ECMAScript 5, there was no good way to enforce privacy on object properties (as you might find in the classical C++ based languages like Java, PHP, etc). ECMAScript 5 and above allow you to assign attributes to properties for things like writability, enumerability, etc...

However, as it pertains to var, well, var always makes its variables private to the function object. You cannot access a var variable from external, client code like this

dog.age = 5 //Trying to assign the number five to a var variable.

You can make a function that has access (known as an accessor), though. In effect, when you see var, think private to this object's scope. That's the gist of it. Closure (from enclosure) is an important subject in JavaScript. When you get into using var, inevitably you start to learn about closure.

3) No key word.

Finally, using naked variables attaches all of them to the global object (window, for most user-agents). This tends to lead to confusion and debugging issues. You may inadvertently stage a collision or conflict where a value is being changed across many instances of your constructor function. It's just not the way to go.

In summary, a fantastic book on the subject of JavaScript variables is The Principles of Object Oriented JavaScript. Mr. Zakas explains things much better than Crockford and Flannagan. I highly recommend it. Know your goal. Know your problem. Avoid global variables. Learn about JavaScript's object mode and scope. I recommend JavaScript: The Definitive Guide when it comes to learning about scope and context in JavaScript.

In jquery, I have a problem. There is a word welcome that should appear for 10 seconds.

After 10 seconds this should disappeared and another word bye should appear for another 10 seconds this should continued like a cycling process.

Can anyone help me out with this problem????

Due to the lack of detail (and a slight smell of homework) I'm only going to give very general advice.

You need to do something after a time interval. jQuery doesn't have that built in, but it's simple enough to do without it: https://developer.mozilla.org/en/DOM/window.setTimeout

It sounds like you need to update text, jQuery can do that: http://api.jquery.com/text/

It is imperative to lean Javascript even while using jQuery. A good book can help there, something along the lines of this one. http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/ref=pd_sim_b_2

Strangely enough, the two answers that were posted while I was writing these have the exact same code, down to formatting and naming. And as such, they both contain a mistake.

I am playing with Javascript accessor properties (I am restarting from zero to study javascript), trying to create getter and setter for a simple object, here the code:

var dummy = {
        name: 'empty',
        description: 'static description',

        get nameAccessor(){return 'name value is: ' + this.name;},
        set nameAccessor(value){ this.name = value;},

        get descAccessor(){return 'desccription value is: ' + this.description;},
};

console.log(dummy.nameAccessor);
console.log(dummy.nameAccessor('Mazinga'));
console.log(dummy.nameAccessor);

But it throws an error:

Uncaught TypeError: Property 'nameAccessor' of object # is not a function

when it executes the setter code:

    console.log(dummy.nameAccessor('Mazinga'));

What's going wrong here?

EDIT:

Ok, it seems to be not a well-known feature of javascript, butI followed this example from Javascript: Definitive Guide

var o = { 
          data_prop: value,
          get accessor_prop() { /* function body here */ },
          set accessor_prop(value) { /* function body here */ }
    };

An accessor is not a function as a property of the object ("method"), but a function that is called when that property is assigned (set) or retrieved (get). Use

dummy.nameAccessor = 'Mazinga';

to invoke the setter function.

In contrast, dummy.nameAccessor('Mazinga') gets the property "nameAccessor" (which results in the name string) and then tries to call it as a function, which will fail. It would work if your getter returned a function, but that is not what you want here.

I have a form created where user will select yes if they "have something". I am using it inside a form which has a post action and then values get sent to .php file. When I try to check the button using if (isset($_POST['agentsele'])) it will not read back. I have some print statements inside to test but it never goes through. I turned the input field from a button to a checkbox and tried it read it - it worked. After I turned it back no go.

Here the the input field.

<input type="button"  value="Yes" name="agentsele" class="agentsele"/>

The check method.

if (isset($_POST['agentsele'])) {

                $emailaction = 1;//email agent and set status to - enrolled - agent emailed
                echo "agent selected";
                exit;
            }

I also have some JQuery that will make more input boxes slide down if the button is selected.

Thank you for your time.

UPDATED -------------------- ENTIRE FORM

<form name="theform" action="insert.php" method="post" >
                <div class="CheckBoxContainer">
            <input type="checkbox" value"On" name="only-thisform"/>
            <?php 
            $setError=$_GET['seterror'];

            if ($setError == 1){

                echo "<div class='errorMsg'> *Required</div>";
            }
             ?>
            <br>
            <br>

            <input type="checkbox"  value="On" name="approval" id="approval"/>
             <?php 
             $setError=$_GET['seterror'];
             if ($setError == 1){

                echo "<div class='errorMsg'> *Required</div>";
             }

             ?>
            </div><!------------------------------------END   .CheckBoxContainer ------------------------------------------->
            <br>
            <br>


<script type="text/javascript"
     src="http://code.jquery.com/jquery-latest.min.js">
</script>   
<!-- javascript on client-side -->


<div class="DropDownSelector">
<?php

$dropdown = "<select name='CompanyNames' id='CompanyNames' >";

$dropdown .= "\r\n<option  id ='' name ='' value='' class=''  ></option>";

$dropdown .= "\r\n<option  id ='other' name ='other' value='other' class='other'  >other</option>";

while($row =$FNresult->fetch()) {

  $dropdown .= "\r\n<option  id ='firstname' name ='first' value='{$row['CompanyNames']}'>{$row['CompanyNames']}</option>";
}

$dropdown .= "\r\n</select>";

echo $dropdown;
?>
    <div class="DropdownDiscription">Please select your insurance company.  Select other if you do not see it listed. </div>
</div> <!------------------------------------------END .DropDownSelector -------------------------------------------------------->
<script type="text/javascript">  

var dropdown = $('#CompanyNames');
//var test = $('#firstname');
//document.write(dropdown.val());

dropdown.bind('change', function(){

     if(dropdown.val() == "other"){
        $(".otherbox").slideDown(1000,function(){
           // $(this).css("border", "2px red inset")            
        });  
         $(".InputDiscriptionother").slideDown(1000,function(){
           // $(this).css("border", "2px red inset")            
        });          
    }else{
          $(".otherbox").slideUp(1000); 
           $(".InputDiscriptionother").slideUp(1000);   
    }

    $.post('backgroundScript.php', 
        { 
            'CompanyNames': dropdown.val()

        },
        function(response) {
            $('#compname').val(response.Companyname);
            //$('#phone').val(response.phone);
            //$('#policynum').val(response.policynum);
            //$('#nameofPolicyholder').val(response.policyholder);
            //$('#mailing').val(response.mailing);
            // Repeat for all of your form fields
        },
        'json'
    );

});
</script>
<br>


<!--<input type="text" class="otherbox" />
<input type="text" class="otherbox" />

<input type="text" class="otherbox"/>-->

<div class="FormBody">

    <div class="InputContainer">
<span class="InputDiscriptionother">Insurance Company Name: </span><div class="InputInner"> <input type="text" name="compname" id="compname" class="otherbox" ></div><!----- END .InputInner ---------->

<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>

</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
    <div class="InputContainer">
<span class="InputDiscription">Insurance Phone number: </span><div class="InputInner"><input type="text"  name="phone" id="phone" ></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>

</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
     <div class="agensele"> Do you have an agent? <input type="button"  value="Yes" name="agentsele" class="agentsele"/></div><!----- END .InputInner ---------->
     <?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required only if selected</span>";
    }
else
    //echo "<span>*</span>"; 
?>
     <div class="noagensele"> Do you have an agent? <input type="button"  value="No" name="noagentsele" class="noagentsele"/> </div><!----- END .InputInner ---------->
</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
<span class="agent">Agent Name: </span><div class="InputInner"> <input type="text" name="agentname"  class="agentinput" ></div><!----- END .InputInner ---------->



</div><!---------------------------------END .InputContaienr ----------------------------------->

<div class="InputContainer">
<span class="agent">Agent Phone Number: </span><div class="InputInner"> <input type="text" name="agentphone"  class="agentinput" ></div><!----- END .InputInner ---------->



</div><!---------------------------------END .InputContaienr ----------------------------------->
<div class="InputContainer">
<span class="agent">Agent's Email: </span><div class="InputInner"> <input type="text" name="agentemail"  class="agentinput" ></div><!----- END .InputInner ---------->



</div><!---------------------------------END .InputContaienr ----------------------------------->
<div class="InputContainer">
<span class="agent">Confirm Agent's Email: </span><div class="InputInner"> <input type="text" name="agentemailone"  class="agentinput" ></div><!----- END .InputInner ---------->



</div><!---------------------------------END .InputContaienr ----------------------------------->
<script>
$(".agentsele").click(function () {
    $(this).css({ borderStyle:"inset", cursor:"wait" });
    //dropdown.bind('change', function(){   
    $(".agentinput").slideDown(1000,function(){
    });
    $(".agent").slideDown(1000,function(){
    });
    //$(".agentsele").css("visibility", "hidden");
    //$(".agensele").css("visibility", "hidden");
    $(".noagentsele").css("visibility", "visible");
    $(".noagensele").css("visibility", "visible");
});
$(".noagentsele").click(function () {
    $(this).css({ borderStyle:"inset", cursor:"wait" });
    //dropdown.bind('change', function(){   
    $(".agentinput").slideUp(1000,function(){
    });
    $(".agent").slideUp(1000,function(){
    });
    $(".agentsele").css("visibility", "visible");
    $(".agensele").css("visibility", "visible");
    $(".noagentsele").css("visibility", "hidden");
    $(".noagensele").css("visibility", "hidden");
});

</script>

<br>
    <div class="InputContainer">
    <span class="InputDiscription">Name of the Policyholder: </span><div class="InputInner"><input type="text" name="nameofPolicyholder" id="nameofPolicyholder"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>

</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
     <div class="InputInner"> Not the Policy Holder? <input type="checkbox"  value="On" name="notpolicyholder" class="notpolicyholder"/></div><!----- END .InputInner ---------->
</div><!---------------------------------END .InputContaienr ----------------------------------->

<br>
    <div class="InputContainer">
<span class="InputDiscription">Policy Number: </span><div class="InputInner"><input type="text" name ="policynum" id="policynum" ></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
    <div class="InputContainer">
<span class="InputDiscription">Policyholder mailing address: </span><div class="InputInner"><input type="text" name="mailing" id="mailing"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>

</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
    <div class="InputContainer">
<span class="InputDiscription">City: </span><div class="InputInner"><input type="text" name="city" id="city"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
    <div class="InputContainer">
    <!------------------------------------------STATE SELECTION CODE ------------------------------------------->
<?php
    function state_select ($name,$full_state,$selected = '') {

  $state_list = array("AL|Alabama","AK|Alaska","AZ|Arizona", "AR|Arkansas", "CA|California", "CO|Colorado", "CT|Connecticut", "DE|Delaware", "DC|Washington D.C.", "FL|Florida", "GA|Georgia", "HI|Hawaii", "ID|Idaho", "IL|Illinois", "IN|Indiana", "IA|Iowa", "KS|Kansas", "KY|Kentucky", "LA|Louisiana", "ME|Maine", "MD|Maryland", "MA|Massachusetts", "MI|Michigan", "MN|Minnesota", "MS|Mississippi", "MO|Missouri", "MT|Montana", "NE|Nebraska", "NV|Nevada", "NH|New Hampshire", "NJ|New Jersey", "NM|New Mexico", "NY|New York", "NC|North Carolina", "ND|North Dakota", "OH|Ohio", "OK|Oklahoma", "OR|Oregon", "PA|Pennsylvania", "RI|Rhode Island", "SC|South Carolina", "SD|South Dakota", "TN|Tennessee", "TX|Texas", "UT|Utah", "VT|Vermont", "VA|Virginia", "WA|Washington", "WV|West Virginia", "WI|Wisconsin", "WY|Wyoming");

  ?>
  <select name=<?=$name;?> id="state" onChange="submitform()"><?
    foreach ($state_list as $s) {
        $values = explode("|",$s);
        ?><option value="<?=$values[0];?>" <?
                if($selected == $values[0]) { ?>SELECTED<? }
                ?>>

                <?  if($full_state) { ?><?=$values[1];?><? } else { ?><?=$values[0];?><? } ?></option><?
    }
  ?></select><?
}
?>

<span class="InputDiscription">State: </span><div class="InputInner">
<?=state_select('state',false,'AL'); ?>
<input type="hidden" id="hiddenfield" name="hiddenfield" value="">
 </div><!----- END .InputInner ---------->

<?php

 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 

?>

</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
<span class="InputDiscription">Zipcode: </span><div class="InputInner"><input type="text" name="zipcode" id="zipcode"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<br>
<div class="InputContainer">
<span class="InputDiscription">Year Of Vehicle: </span><div class="InputInner"><input type="text" name="YearOfVehicle" id="YearOfVehicle"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
<span class="InputDiscription">Make Of Vehicle: </span><div class="InputInner"><input type="text" name="MakeOfVehicle" id="MakeOfVehicle"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
<span class="InputDiscription">Model Of Vehicle: </span><div class="InputInner"><input type="text" name="ModelOfVehicle" id="ModelOfVehicle"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
<span class="InputDiscription">Vehicle Identification Number: </span><div class="InputInner"><input type="text" name="Vehicleid" id="Vehicleid"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
<span class="InputDiscription">Policy Effective Date: </span><div class="InputInner"><input type="text" name="Policyeffdate" id="Policyeffdate"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
<span class="InputDiscription">Policy Expiration Date: </span><div class="InputInner"><input type="text" name="Policyexpdate" id="Policyexpdate"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<br>
<h2>Employee Information</h2>

<div class="InputContainer">
<span class="InputDiscription">Employee Name: </span><div class="InputInner"><input type="text" name="EmployeeName" id="EmployeeName"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<br>
<div class="InputContainer">
<span class="InputDiscription">Employee Company Name: </span><div class="InputInner"><input type="text" name="EmployeeCompanyName" id="EmployeeCompanyName"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
<span class="InputDiscription">Agency/Franchise Number (or unique indicator): </span><div class="InputInner"><input type="text" name="Agency/FranchiseNumber" id="Agency/FranchiseNumber"></div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="InputContainer">
<span class="InputDiscription">Todays Date: </span><div class="InputInner"><input type="text" name="TodaysDate" id="TodaysDate" value="
<?php

$today = date("n-j-Y"); 
echo $today;
?>">
</div><!----- END .InputInner ---------->
<?php
 $setError=$_GET['seterror']; 
if($setError == 1){
    echo "<span class='errorMsg'>*Required</span>";
    }
else
    //echo "<span>*</span>"; 
?>


</div><!---------------------------------END .InputContaienr ----------------------------------->
<br>
<div class="CheckBoxContainer">
            <input type="checkbox" value"On" name="correct"/>The above printed name serves to identify the employee and shows intent of the employee that the above auto insurance information given is accurate.  
            <?php 
            $setError=$_GET['seterror'];

            if ($setError == 1){

                echo "<div class='errorMsg'> *Required</div>";
            }
             ?>
            <br>
            <br>

            <input type="checkbox"  value="On" name="agree" id="agree"/>The employee identified above confirms this document has been read, reviewed and understood and subsequently authorizes it as such. 
             <?php 
             $setError=$_GET['seterror'];
             if ($setError == 1){

                echo "<div class='errorMsg'> *Required</div>";
             }

             ?>
             <br>
             <br>
             <input type="checkbox"  value="On" name="understood" id="understood"/>The employee understands that if inaccurate information is discovered on the above auto insurance information table, on the employee's auto policy itself or if the auto insurance policy is cancelled for any reason, the employer will be notified. 
             <?php 
             $setError=$_GET['seterror'];
             if ($setError == 1){

                echo "<div class='errorMsg'> *Required</div>";
             }

             ?>
            </div><!------------------------------------END   .CheckBoxContainer ------------------------------------------->
            <br>
<?php 
 $setError=$_GET['seterror']; 
if($setError == 1){
echo "<script type='text/javascript'>alert('Please check to make sure all required fields are filled out!');</script>";
}
?>


<input type="Submit" name="Submit" >

</div><!-------------------------------------------END .FormBody ------------------------------------------------------->
</form>

UPDATED-------------------

When I changed type to submit it worked but I do not want it to send me straight to the function where it inserts data. How do I stop it from submitting.

First, we could try standardizing your control.

<input type="submit" name="Submit" value="Submit" /> 

http://www.w3.org/TR/html401/interact/forms.html#h-17.4


Perhaps some clarification about buttons could help, too.

http://www.w3.org/TR/html401/interact/forms.html#h-17.5


"When I changed type to submit it worked but I do not want it to send me straight to the function where it inserts data. How do I stop it from submitting."

I'm a little rusty with my JavaScript, but I believe you can use the onsubmit attribute to do something, or you can register some functions using the onload="" attribute of the <form> tag or, more commonly, the <body> tag. Find a good JavaScript book with a section on forms.

http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/ref=sr_1_1?s=books&ie=UTF8&qid=1401399613&sr=1-1&keywords=javascript+the+definitive+guide

I'm a beginner to Javascript and am trying to make sense of why something's not working. I created a simple page with some reference arrays in the <head> section which I could then access in the <body> So the head section looks like this:

<!DOCTYPE html>
<html>
  <head>
    <script>
      var cities = [ "London", "New York" ];
    </script>
  </head>

The I want to use this array to drive a dropdown in the body of the HTML so I thought I'd use this:

<body>
  <select id="dd_city">
    <script>
      for( i = 0; i < cities.length; i++)
      {
        document.write( "<option value=" + i + ">" + cities[i] + "</option>" )
      }
    </script>
  </select>
  ...

I thought that this would be reasonable and it was based on examples I found online. however, I find that it just produces an empty drop down, as if the array is seen as empty. What have I misunderstood or got wrong?

where to begin... first of all it is considered good practice to put your javascript at the bottom of the document right before the closing body tag. see the following link for an explanation as to why that is:

http://developer.yahoo.com/performance/rules.html#js_bottom

when you include javascript files at the bottom of the document you will be forced to enclose your code into functions and bind those functions to different events. javascript is very much an event driven language.

this will encourage you to write better code that will be reusable throughout your project. I wont go into a big long lecture on writing good code but i recommend picking up a good book to get you started. like Javascript The Definitive Guide.

as to the code you currently have, here's how I would do it:

<!DOCTYPE html>
<html>
    <head>
    </head>

    <body>
      <select id="dd_city"></select>
      <script>
          var initPage = function() {
              var cities = Array("London", "New York");
              var selectBox = document.getElementById("dd_city");

              for( var i = 0; i < cities.length; i++)
              {
                  var option = document.createElement("option");

                  option.setAttribute("value", i);
                  option.innerHTML = cities[i];
                  selectBox.appendChild(option);
              }
          };

          window.onload = initPage();
      </script>
    </body>
</html>

see it in action at my jsfiddle.

I want to build my own Javascript library for this I need to master in OOP concepts to apply in Javascript. Please suggest me a reference which gives more examples with explanation.

Thank you in advance.
Shishir Kumar M.

Pick up some books on Javascript programming. I highly recommend O'Rielly's Javascript The Definitive Guide by David Flanagan or one of O'Rielly's many other books on Javascript. I personally learned a great deal from them.

Recently I started learning Javascript as I am comming from Java world. I got this book called JavaScript The Definitive guide.. I am now a little confused about Prototypes and Inheritance. I want to know what is difference between setting a function to object property and functions prototype. From the book example :

function Rectangle(w, h) {
this.width = w;
this.height = h;
this.area = function( ) { return this.width * this.height; }
}

With this new version of the constructor, you can write code like this:

// How big is a sheet of U.S. Letter paper in square inches?
var r = new Rectangle(8.5, 11);
var a = r.area( );

This solution works better but is still not optimal (why) . Every rectangle created will have three properties ( Yes, and so what ? ). The width and height properties may be different for each rectangle, but the area of every single Rectangle object always refers to the same function (someone might change it, of course, but you usually intend the methods of an object to be constant). It is inefficient to use regular properties for methods that are intended to be shared by all objects of the same class (WHY ??? What is the problem ? ) (that is, all objects created with the same constructor).

Rectangle object always refers to the same function

That's incorrect. Every rectangle object will have its own copy of a function assigned to area property.

While if you used a prototype-based definition you would have a single function shared across all the instances.

So from the performance and memory consumption point of view it's better to define it as

Rectangle.prototype.area = function() {
    return this.width * this.height;
};

Some Background Information

I have been mainly into java development(Java EE frameworks) since around a year , now recently I've made to switch to mobile applications using appcelerator titanium targeting both android and iOS. It's been around three months working with titanium and we've released our first build. (It's an In house App)

Problem ??

As you probably know , we code in java script in titanium and It's wraps code into corresponding target platform. Now, my experience with java script is limited to writing client side form validation (DOM).and that's it.So I decided to fix it.
Now I started to learn java script by following this and this. and video lectures of douglas crockford.

Question ?
Since java (OOPS ?) is bloated deeply in my mind i have very hard time following java script , every thing i see from the eyes of java , (Inheritance , type saftey, exception handling , constructors , instance , static, access modifiers....)
I know java script have support for first class function and built in Objects to work with , however i cant just differentiate between the two,and when i see something like this I don't have a clue at first place.

So , How to tackle with this situation ?

PS: Though this may be rather subjective but I am sure it would be useful for those whose's having hard time learning JavaScript from oops background.

First off, let me make a point: it's a good thing(tm) that you feel Javascript is so foreign and uncomfortable. We programmers grow and learn the most by leaving our comfort zone, which is why you'll find countless SO answers arguing that you should learn language X, even if you never plan to use it, just to grow as a programmer. So as distasteful as you're finding this process, it's good for you, like spinach ;-)

As with learning any programming language though, the rules are pretty simple:

  1. Get a good basic language reference. There are countless websites you can use (but remember, W3Schools == evil/outdated). As Floydian mentioned there is Crockford's "The Good Parts". Personally I learned a ton just from my stupid $10 O'Reilly Javascript pocket reference. And I'm sure there are lots of other great references out there (I'd imagine anything with 4-5 stars on Amazon is worthwhile).
  2. Tackle a demo project. Depending on what book/website you picked they might have a tutorial activity for you, but if not just make up your own and try to accomplish it as you learn
  3. Once you have the basics down, throw jQuery in to the mix; it's basically Javascript 2.0 at this point (again, there are lots of great books/sites to choose from, including jquery.com, which has excellent documentation). Other frameworks are worth learning too (for instance, Backbone is a great MVC/OOP(kinda) framework), but I'd stick to just jQuery and Javascript at first until you are comfortable with jQuery
  4. Throw in those other libraries, or other tools like testing frameworks (QUnit and JS Test Driver both being excellent options). You're getting close to JS Ninja status now.
  5. Check out more advanced resources (eg. the Javascript Ninja one by John Resig, jQuery's creator).
  6. Go through the answers on Advanced JavaScript Interview Questions. Can you answer all of the questions in them yet? If not, go learn more about that topic.
  7. Finally able to answer everything in that thread? Congratulations: you can now say (in your best Keanu Reeves voice) "I know JS-Fu!"