1 / 30

JavaScript Events, DOM & Forms

onClick , innerHTML , getElementById. JavaScript Events, DOM & Forms. JavaScript Events, working with the Document Object Model, working with forms. Event Handlers.

guy-mays
Download Presentation

JavaScript Events, DOM & Forms

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. onClick, innerHTML, getElementById JavaScript Events, DOM & Forms JavaScript Events, working with the Document Object Model, working with forms

  2. Event Handlers • With an event handler, you can do something with an element when an event occurs, i.e., when the user clicks an element, when the page loads, when a form is submitted, timed events etc. • An event handler may be included within any XHTML tag; however, not all tags support all event handlers. • The example below defines a header that turns red when a user clicks on it. <h1 onclick="this.style.color='red'"> Click on this text</h1> • You can also add a script in the head section of the page and then call the function from the event handler: <html> <head> <script type="text/javascript"> function changecolor() { document.getElementById('header') .style.color="red" } </script> </head> <body> <h1 id="header" onclick="changecolor()"> Click on this text</h1> </body> </html> changeHeader.html

  3. Buttons • You can associate buttons with JavaScript events • buttons in HTML forms <FORM> <INPUT TYPE=BUTTON VALUE="Don't Press Me" onClick="alert('now you are in trouble!')“ > </FORM>

  4. Some Events (a small sample) onUnLoad onLoad onClick onMouseUp onMouseDown onDblClick onMouseOver Window events Button events Link events

  5. ONLOAD event • The onLoad event is triggered when an element is loaded by the browser. • You can put an onLoadhandler in the BODY tag: <BODY onLoad="alert('Welcome');"> <H1>A title</H1> <P>Here is a paragraph …

  6. Another onLoad example <SCRIPT> function start() { window.setInterval("updateTime()",1000); } var seconds=0; function updateTime() { seconds++; document.getElementById("time").innerHTML = seconds; } </SCRIPT> <BODY onLoad="start();"> <H1>Sample Document</H1> <H3>You have been here <B ID=time>0</B> seconds.</H3>

  7. Document Object Model • Access individual elements of a HTML document. • Easy to use if you name all entities: • Forms, fields, images, etc. <FORM ID=myform ACTION=… > Please Enter Your Age: <INPUT TYPE=TEXT ID=age NAME=age><BR> And your weight: <INPUT TYPE=TEXT ID=weight NAME=weight><BR> </FORM> Using JavaScript you can get the value of the age input field: document.myform.age.value

  8. HTML Forms and JavaScript • JavaScript is very good at processing user input in the web browser • HTML <form> elements receive input • Forms and form elements have unique names • Each unique element can be identified • Uses JavaScript Document Object Model (DOM)

  9. Naming Form Elements in HTML <form name="addressform"> Name: <input name="yourname"><br /> Phone: <input name="phone"><br /> Email: <input name="email"><br /> </form>

  10. Forms and JavaScript document.formname.elementname.value Thus: document.addressform.yourname.value document.addressform.phone.value document.addressform.email.value

  11. Using Form Data Personalising an alert box <form name="alertform"> Enter your name: <input type="text" name="yourname"> <input type="button" value= "Go" onClick="window.alert('Hello ' + document.alertform.yourname.value);"> </form>

  12. Document Object Model • The Document Object Model provides access to every element in a document. Because of that access, any element may be modified by a snippet of JavaScript. • Elements are easily accessed by use of an id attribute and the getElementById method of the document object. • Note that the value of the id attribute must be unique within a given document. I.e., You cannot have two elements with the same id within the same document. • The script changes the color of the header element <html> <body> <h1 id="header">My header</h1> <script type="text/javascript"> document.getElementById('header').style.color = "red" </script> </body> </html> Any element, which contains an id attribute, may be referenced by the getElementById() method. Pass it the value of the id attribute and you may then reference any properties, methods, or collections of the element. I.e., the text color of the element, whose id is 'header', is referenced by document.getElementById('header').style.color

  13. DOM: InnerHTML • Use innerHTML function to access the contents—the code—contained in an object. • For example, given a paragraph whose id = "sample", its innerText and innerHTML may be accessed via: document.getElementById('sample').innerHTML • By manipulating the innerHTML property you can change, dynamically, the text on a page (without reloading the page). • The content of an object is interpreted as HTML with the innerHTML function. • innerHTML = <b>inner text</b>" would display as inner text.

  14. DOM: InnerHTML Recall that the <div></div> tag is often used To define a region within a page so that it can encompass several page elements, such as several paragraphs or a paragraph and a table. The innerHTML, style properties, etc. of the entire div can be changed. I.e., change the div (id="d1") to red; to purple; to yellow; change the innerHTML of the div. <script type="text/javascript"> function ChangeInnerHTML(theID, theHTML) { if (typeoftheHTML == "undefined") { theHTML = window.prompt("Please specify innerHTML", "<b>hello world</b>"); } document.getElementById(theID).innerHTML = theHTML; } function ChangeColor(theID, theColor) { document.getElementById(theID).style.backgroundColor = theColor; } </script> <div id="d1"> </div> change the div (id="d1") to <a href="javascript:ChangeColor('d1','red');">red</a>; … <a href="javascript:ChangeInnerHTML('d1');">change the innerHTML of the div</a>. changeDiv.html

  15. Example id="box1" <body> <textarea id="box1"></textarea> <input type="button" value="update" onclick="update()" /> <p id="message">This is a message box.</p> </body> id="message"

  16. Example <head> <script> function update(){ document.getElementById("message").innerHTML = document.getElementById("box1").value; } </script> </head>

  17. DOM: Forms - Form Fields • You can use the DOM to get the value of a form field, or to set the value of a form field. • Assign an ID to each form field. • use the value attribute to access the current value.

  18. DOM: Forms - Form Field Example Name: <INPUT ID=nfield TYPE=TEXT><BR> <INPUT TYPE=BUTTON VALUE="Check" onClick="validate();"> <SCRIPT> function validate() { fld = document.getElementById("nfield"); if (fld.value != "Dave") { alert("The name you typed is wrong"); fld.value="Dave"; } } <SCRIPT> formexample.html

  19. Naming Form Elements in HTML <form name="addressform"> Name: <input id="yourname" name="yourname"><br /> Phone: <input id="phone" name="phone"><br /> Email: <input id="email" name="email"><br /> </form>

  20. Forms and JavaScript document.getElementById("elementname").value Thus: document.getElementById("yourname").value document.getElementById("phone").value document.getElementById("email").value

  21. Simple Form Access (setting a value)  function toggle() { if(document.simpleform.simpleinput.value == "Hello") document.simpleform.simpleinput.value = "World"     else document.simpleform.simpleinput.value = "Hello"     }  Or     function toggle() {           if(document.getElementById("simpleinput").value == "Hello") document.getElementById("simpleinput").value = "World";           else document.getElementById("simpleinput").value = "Hello";     } <form name="simpleform"> <input type="text" name="simpleinput" value="Hello"> <input type="button" name="simplebutton" value="Go" onClick="toggle()"> </form> Or <form id="simpleform" action="DOM -- SimpleFormAccess.html"> <div>   <input type="text" id="simpleinput" value="Hello" />   <input type="button" id="simplebutton" value="Go" onclick="toggle()" /> </div> </form>

  22. Exercise • Create a web page that looks as follows: When the user clicks "Generate Song", the phrase "round and round" will be repeated the specified number of times after "The wheels on the bus go".

  23. The Wheels On The Bus Go… <div> Times: <input type="text" id="times" /><br /> <input type="button" value="Generate Song" onclick="generate();" /> <p id="output"> </p> </div> HTML function generate() { var times = document.getElementById("times").value; var text = "The wheels on the bus go "; for (var i = 1; i <= times; i++) { text = text + "round and round "; } document.getElementById("output").innerHTML = text; } JavaScript

  24. The Wheels On The Bus Go… • Can shorten text = text + ... to text += ... function generate() { var times = document.getElementById("times").value; var text = "The wheels on the bus go "; for (var i = 1; i <= times; i++) { text += "round and round "; } document.getElementById("output").innerHTML = text; } JavaScript

  25. Create a web page that looks as follows (example values filled in): When the user clicks "Generate Sentences", the text will be repeated the specified number of times. Exercise

  26. Solution <div> Text: <input type="text" id="text" /><br /> Times: <input type="text" id="times" /><br /> <input type="button" value="Generate Sentences" onclick="generate();" /> <p id="output"> </p> </div> HTML function generate() { var times = document.getElementById("times").value; var sentence = document.getElementById("text").value; var text = ""; for (var i = 1; i <= times; i++) { text += sentence + "<br />"; } document.getElementById("output").innerHTML = text; } JavaScript

  27. Exercise: Radio Buttons <label> <input type="radio" name="cards" id="cards1" value="MasterCard" onchange="showCard(1);" />MasterCard </label> <label> <input type="radio" name="cards" id="cards2" value="Visa" onchange="showCard(2);" />Visa </label> <label> <input type="radio" name="cards" id="cards3" value="Discover" onchange="showCard(3);" />Discover </label> HTML function showCard(num) { var value = document.getElementById("cards" + num).value; alert("You picked: " + value); } JavaScript

  28. Exercise: Radio Buttons <label> <input type="radio" name="cards" id="cards1" value="MasterCard" onchange="showCard();" />MasterCard </label> <label> <input type="radio" name="cards" id="cards2" value="Visa" onchange="showCard();" />Visa </label> <label> <input type="radio" name="cards" id="cards3" value="Discover" onchange="showCard();" />Discover </label> • It is possible to use the same parameter-less function. • Use document.getElementById("<ID>").checked to see if each radio button is activated • The checked attribute is a Boolean value (true or false). HTML

  29. Exercise: Radio Buttons function showCard() { if (document.getElementById("cards1").checked) { var value = document.getElementById("cards1").value; alert("You picked: " + value); } if (document.getElementById("cards2").checked) { var value = document.getElementById("cards2").value; alert("You picked: " + value); } if (document.getElementById("cards3").checked) { var value = document.getElementById("cards3").value; alert("You picked: " + value); } } JavaScript

  30. Exercise: Radio Buttons • Can loop over element IDs • Although the previous slide is acceptable as a solution in this class, you should learn to make the computer do most of the work for you as above. function showCard() { for (vari = 1; i <= 3; i++) { varidToTry = "cards" + i; if (document.getElementById(idToTry).checked) { var value = document.getElementById(idToTry).value; alert("You picked: " + value); } } } JavaScript

More Related