Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

October 8, 2011

Timer Interval functions in Javascript

Code Example


<html>
<head>
<script type="text/javascript">

var timerId;

var setAlerts = function() {
   timerId = setInterval("myfunction();",3000);
}

var removeAlerts = function() {
   clearInterval(timerId);
}

function myfunction() {
   alert("Hi");
}

window.onload = function() {
   document.getElementById("setButton").onclick=setAlerts;
   document.getElementById("clearButton").onclick=removeAlerts;
}

</script>
</head>
<body>

<button id="setButton">Set Interval</button><br/>
<button id="clearButton">Clear Interval</button><br/>

</body>
</html>

Javascript to set cookies and get hold of a specific cookie

Write Javascript code to store a cookie and retrieve it - also check if cookies are enabled on the client.

Solution

<html>
<head>
<script type="text/javascript">

var cookieFunction = function() {
   
if (navigator.cookieEnabled) {
var name = prompt("Enter cookie name");
      var value= prompt("Enter cookie value");
      if ((name) && (value)) {
         var date = new Date("1 Jan 2015 11:30:00");
         document.cookie= name + "="+value+"; expires="+date.toGMTString()+";";
      }
   } else {
      alert("Cookies Not enabled");
   }
}

var getCookie = function() {
   var cookies=document.cookie;
   alert(cookies);
}

var getSpecificCookie = function() {
   var c_name = prompt("Enter cookie name");
   var all_cookies = document.cookie.split( ';' );
   for (i=0;i<all_cookies.length;i++) {
      x = all_cookies[i].substr(0, all_cookies[i].indexOf("="));
      y = all_cookies[i].substr(all_cookies[i].indexOf("=")+1);
      x = x.replace(/^\s+|\s+$/g,"");
      if (x == c_name) {
        alert( unescape(y));
        return;
     }
   }

   alert("Cookie does not exist");
}

window.onload = function() {
   document.getElementById("getCookieButton").onclick=getCookie;
   document.getElementById("getSpecificCookieButton").onclick=getSpecificCookie;
   document.getElementById("diceButton").onclick=rollDice;
}

</script>
</head>
<body>
<button id="cookieButton">Set Cookie</button>
<button id="getCookieButton">Get Cookies</button>
<button id="getSpecificCookieButton">Get Specific Cookie</button>

</body>
</html>

Javascript simulation of rolling of a dice


Write Javascript code to simulate the rolling of a dice. When the user clicks a button, the result should be the simulation of a dice - a value between 1 to 6 is displayed in the String, "Your roll of the dice displayed 3"

Hint: Math.random(), document.getElementById(), innerHTML, onclick event

Solution


<html>
<head>
<script type="text/javascript">

var rollDice = function() {
   var diceElementNode = document.getElementById("diceValue");
   var diceElementNodeChildren = diceElementNode.childNodes;

   if (diceElementNodeChildren[0] != null) {
      diceElementNodeChildren[0].nodeValue = "The dice value is " + Math.ceil((Math.random() * 6));
   } else {
      var diceTextNode = document.createTextNode("");
      diceTextNode.nodeValue ="The dice value is " + Math.ceil((Math.random() * 6));
      diceElementNode.appendChild(diceTextNode);
   }
}

window.onload = function() {
   document.getElementById("diceButton").onclick=rollDice;
}

</script>
</head>
<body>
<button id="diceButton">Roll Dice</button>
<div id="diceValue"></div>

</body>
</html>

May 8, 2011

Javascript DOM Manipulation

Write Javascript code to manipulate a webpage using DOM manipulation, to do the following,
   - click a button to simulate rolling of a dice ( use Math.random() )
   - click of a button to add more fields to a form/add a different textfield/label pair based on selection of 2 possible options on a radio button

Solution

<html>
  <head>
    <script type="text/javascript">

    var rollDice = function() {
        var diceElementNode = document.getElementById("diceValue");
 
        diceElementNode.innerHTML = "The dice value is " + 
                           Math.ceil((Math.random() * 6));
    }

    var addAddressFields = function() {
        var formElementNode = document.getElementById("formElement");

        var streetAddressNode = document.createElement("input");
 
        var typeAttribStreetAddress = document.createAttribute("type");
        typeAttribStreetAddress.nodeValue="text";
        streetAddressNode.setAttributeNode(typeAttribStreetAddress);
 
        var nameAttribStreetAddress = document.createAttribute("name");
        nameAttribStreetAddress.nodeValue="street";
        streetAddressNode.setAttributeNode(nameAttribStreetAddress);

        formElementNode.appendChild(document.createTextNode("Street: "));
        formElementNode.appendChild(streetAddressNode);

        formElementNode.appendChild(document.createElement("br"));

        var zipNode = document.createElement("input");
        var typeAttribZip = document.createAttribute("type");
        typeAttribZip.nodeValue="text";
        zipNode.setAttributeNode(typeAttribZip);
        formElementNode.appendChild(document.createTextNode("Zip Code: "));
        formElementNode.appendChild(zipNode);
        formElementNode.appendChild(document.createElement("br"));
        document.getElementById("addressButton").disabled=true;
    }

    window.onload = function() {
        document.getElementById("diceButton").onclick=rollDice;
        document.getElementById("addressButton").onclick=addAddressFields;
    }

    </script>
  </head>
  <body>
    <br/>

    <button id="diceButton">Roll Dice</button>
    <div id="diceValue"></div>

    <br/>
    <br/>

    <form id="formElement">
      First Name: <input type="text" name="firstname"/><br/>
      Last Name: <input type="text" name="lastname"/><br/>
      <button id="addressButton">Click to input address</button><br/>
    </form>

  </body>
</html>

Javascript code to validate phone number, zip code

Write JS code to validate the following fields of a form
   - phone number (format: xxx-xxx-xxxx )
   - zip code (format: xxxxx-xxxx)

Solution

<html>
  <head>
     <script type="text/javascript">

     var validateForm = function() {

        validatePhone();
        validateZipCode();
     }

     var validatePhone = function() {
        var phoneRegexp = /^\d{3}-\d{3}-\d{4}$/;
        var phoneTest = phoneRegexp.test(document.myForm["phone"].value);
   
        if (phoneTest == false) {
            alert("Please enter correct phone number in the format xxx-xxx-xxxx");
            return false;
        }
     }

     var validateZipCode = function() {
        var zipcodeRegexp = /^\d{5}-\d{4}$/;
        var zipTest = zipcodeRegexp.test(document.myForm["zip"].value);
   
        if (zipTest == false) {
            alert("Please enter Zip Code in the format xxxxx-xxxx");
            return false;
        }
     }

     window.onload = function() {
        document.getElementById("Form").onsubmit=validateForm;
     }

     </script>
  </head>

  <body>
     <form name="myForm" id="Form" method="post" action="#">
        Phone<br/>
        <input type="text" name="phone" id="phoneField"/> <br/>
        Zip Code<br/>
        <input type="text" name="zip"/> <br/>
        <input type="submit" value="Submit"/>
     </form>
  </body>

</html>