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>

No comments:

Post a Comment