Presentation is loading. Please wait.

Presentation is loading. Please wait.

Event-driven programs and HTML form elements

Similar presentations


Presentation on theme: "Event-driven programs and HTML form elements"— Presentation transcript:

1 Event-driven programs and HTML form elements

2 Agenda event-driven programs HTML forms & attributes
onload, onunload HTML forms & attributes button, text box, text area selection list, radio button, check box, password, hidden, … JavaScript form events properties: name, type, value, … methods: blur(), focus(), click(), … event handlers: onblur(), onfocus(), onchange(), onclick(), … advanced features & techniques windows & frames, timeouts, cookies

3 برنامه های وابسته به رخداد ها
زبانهای C++ و جاوا معمولا بصورت سریال اجرا می شوند: از تابع main شروع می کنیم و از اولین خط به صورت ترتیبی اجرا می کنیم. ممکن است برنامه دارای حلقه یا کد شرطی باشد، اما در هر صورت اجرای برنامه قدم به قدم خواهد بود. برنامه دارای شروع و پایان است و برنامه به ترتیب دلخواه برنامه نویس اجرا می شود. اما محاسبات درون یک صفحه وب بندرت سریال است. صفحه به رخداد هایی مثل کلیک موس یا دکمه ها جواب می دهد. قسمتی از ابزارهای JavaScript اعمالی را مشخص می کنند که در اثر رخداد ها در صفحه وب واقع می شوند. برنامه نویس کنترل زیادی روی ترتیب اجرای کد ندارد. در واقع هیچ ترتیب اجرایی وجود ندارد و صفحه منتظر است تا به رخداد های پیش آمده واکنش نشان دهد.

4 OnLoad & OnUnload <html> <!–- COMP519 form01.html > <head> <title>Hello/Goodbye page</title> <script type="text/javascript"> function Hello() { globalName=prompt("Welcome to my page. " + "What is your name?",""); } function Goodbye() alert("So long, " + globalName + " come back real soon."); </script> </head> <body onload="Hello();" onunload="Goodbye();"> Whatever text appears in the page. </body> </html> ساده ترین رخداد ها، رخداد های OnLoad و OnUnload هستند. خاصیت OnLoad در برچسپ body به کدی اشاره می کند که هنگام بالا آمدن صفحه وب بطور خودکار اجرا می شود. خاصیت OnUnload در برچسب body به کدی اشاره می کند که هنگام بستن صفحه وب بطور خودکار اجرا می شود. view page

5 HTML forms اکثر رخداد هایی که نیاز به پردازش دارند مربوط به عناصر فرمها هستند. یک فرم HTML مجموعه ای از عناصر جهت کنترل ورودی و خروجی و رخدادهای صفحه است. <form name="FormName"> </form> عناصر فرم: ورودیها: دکمه، لیست رادیویی، دکمه رادیویی، جعبه کنترلی، رمز ورود و ... ورودی وخروجی: جعبه متن، ناحیه متن و .... فرمها در برنامه نویسی CGI نیز استفاده می شوند.

6 Button Element ساده ترین عنصر فرم دکمه است.
کلیک روی دکمه یک رخداد است. <input type="button" value="LABEL" onclick="JAVASCRIPT_CODE"/> <html> <!–- COMP519 form02.html > <head> <title> Fun with Buttons</title> <script type="text/javascript" src=" </script> </head> <body> <form name="ButtonForm"> <input type="button" value="Click for Lucky Number" onclick=“var num = RandomInt(1, 100); alert('The lucky number for the day is ' + num);" /> </form> </body> </html> view page

7 Buttons & Functions <html> <!–- COMP519 form03.html > <head> <title>Fun with Buttons</title> <script type="text/javascript"> function Greeting() // Results: displays a time-sensitive greeting { var now = new Date(); if (now.getHours() < 12) { alert("Good morning"); } else if (now.getHours() < 18) { alert("Good afternoon"); else { alert("Good evening"); </script> </head> <body> <form name="ButtonForm"> <input type="button" value="Click for Greeting" onclick="Greeting();" /> </form> </body> </html> برای کارهای پیچیده تر، تابع مورد نظر را بنویسید و به رخداد onclick دکمه وصل کنید. view page

8 Buttons & Windows جعبه alert برای نمایش پیغامهای کوتاه و غیر معمول مناسب است. اما نمایش پیغامهای طولانی و دارای فرمت نیاز به ابزار مناسب تری دارد. alert جزء صفحه نیست و باید کاربر بصورت صریح آنرا ببندد. سوال: آیا می شود از document.write استفاده کرد؟ خیر – چون کل صفحه را تغییر می دهد. می شود یک پنجره جدید باز نمود و آنجا نوشت: var OutputWindow = window.open(); // open a window and assign // a name to that object // (first arg is an HREF) OutputWindow.document.open(); // open that window for writing OutputWindow.document.write("WHATEVER"); // write text to that // window as before OutputWindow.document.close(); // close the window

9 Window Example view page <html>
<!– COMP519 form04.html > <head> <title> Fun with Buttons </title> <script type="text/javascript"> function Help() // Results: displays a help message in a separate window { var OutputWindow = window.open(); OutputWindow.document.open(); OutputWindow.document.write("This might be a context-" + "sensitive help message, depending on the " + "application and state of the page."); OutputWindow.document.close(); } </script> </head> <body> <form name="ButtonForm"> <input type="button" value="Click for Help" onclick="Help();" /> </form> </body> </html> view page

10 Window Example Refined
<html> <!– COMP519 form05.html > <head> <title> Fun with Buttons </title> <script type="text/javascript"> function Help() // Results: displays a help message in a separate window { var OutputWindow = window.open("", "", "status=0,menubar=0,height=200,width=200"); OutputWindow.document.open(); OutputWindow.document.write("This might be a context-" + "sensitive help message, depending on the " + "application and state of the page."); OutputWindow.document.close(); } </script> </head> <body> <form name="ButtonForm"> <input type="button" value="Click for Help" onclick="Help();" /> </form> </body> </html> می توان به تابع window.open آرگومان فرستاد. آرگومان اول HREF را مشخص می کند. آرگومان دوم نام داخلی را مشخص می کند. آرگومان سوم خواص پنجره را تعیین می کند. view page

11 Text Boxes جعبه متن برای گرفتن ورودی از کاربر استفاده می شود.
برخلاف prompt ورودی کاربر در صفحه باقی می ماند و قابل تغییر است. <input type="text" id=“BOX NAME” name="BOX_NAME"… /> پارامترها: اندازه: پهنای جعبه بر حسب کاراکتر مقدار: متن پیش فرض <html> <!– COMP519 form06.html > <head> <title> Fun with Text Boxes </title> </head> <body> <form name="BoxForm"> Enter your name here: <input type="text" name="userName" size=“12” value="" /> <br /><br /> <input type="button" value="Click Me" onclick="alert('Thanks, ' + document.BoxForm.userName.value + ', I needed that.');" /> </form> </body> </html> view page

12 Read/Write Text Boxes می توان محتوای جعبه متن را توسط دستور انتصاب نیز تغییر داد. نکته: محتوای متن ساده وخام است و از نوع رشته است. اگر می خواهید بصورت عدد استفاده شود از parseFloat و parseInt استفاده کنید. <html> <!– COMP519 form07.html > <head> <title> Fun with Text Boxes </title> </head> <body> <form name="BoxForm"> Enter a number here: <input type="text" size=“12” name="number" value=“2” /> <br /><br /> <input type="button" value="Double" onclick="document.BoxForm.number.value= parseFloat(document.BoxForm.number.value) * 2;" /> </form> </body> </html> view page

13 Text Box Events رخداد onchange وقتی آتش می شود که متن تغییر کند.
<html> <!– COMP519 form08.html > <head> <title> Fun with Text Boxes </title> <script type="text/javascript"> function FahrToCelsius(tempInFahr) // Assumes: tempInFahr is a number (degrees Fahrenheit) // Returns: corresponding temperature in degrees Celsius { return (5/9)*(tempInFahr - 32); } </script> </head> <body> <form name="BoxForm"> Temperature in Fahrenheit: <input type="text" name="Fahr" size=“10” value=“0" onchange="document.BoxForm.Celsius.value = FahrToCelsius(parseFloat(document.BoxForm.Fahr.value));" />   <tt>----></tt>   <input type="text" name="Celsius" size=“10” value="" onfocus="blur();" /> in Celsius </form> </body> </html> رخداد onchange وقتی آتش می شود که متن تغییر کند. رخداد onfocus وقتی آتش می شود که ماوس روی متن کلیک کند. تابع blur()، focus را خاموش می کند. view page

14 Text Box Validation اگر در جعبه متن فارنهایت یک کاراکتر چاپ شود، چکار کنیم؟ می توان مقدار ورودی جعبه متن را اعتبارسنجی کرد. با یک مقدار معتبر شروع کنید. هنگام وقوع onchange، اعتبار مقدار ورودی را بسنجید. از کتابخانه verify.js استفاده کنید. function VerifyNum(textBox) // Assumes: textBox is a text box // Returns: true if textBox contains a number, else false + alert { var boxValue = parseFloat(textBox.value); if ( isNaN(boxValue) ) { alert("You must enter a number value!"); textBox.value = ""; return false; } return true;

15 Validation Example view page <html>
<!– COMP519 form09.html > <head> <title> Fun with Text Boxes </title> <script type="text/javascript" src="verify.js"> </script> <script type="text/javascript"> function FahrToCelsius(tempInFahr) { return (5/9)*(tempInFahr - 32); } </head> <body> <form name="BoxForm"> Temperature in Fahrenheit: <input type="text" name="Fahr" size=“10” value=“0” onchange="if (VerifyNum(this)) { // this refers to current element document.BoxForm.Celsius.value = FahrToCelsius(parseFloat(this.value)); }" />   <tt>----></tt>   <input type="text" name="Celsius" size=“10” value="" onfocus="blur();" /> in Celsius </form> </body> </html> view page

16 Text Areas جعبه متن فقط یک خط ورودی می پذیرد.
<textarea name="TextAreaName" rows=“NumRows” cols=“NumCols”> Initial Text </textarea> TEXTAREA یک برچسپ جفتی است. متن پیش فرض بین این جفت قرار می گیرد.

17 TEXTAREA Example view page
<html> <!– COMP519 form10.html > <head> <title> Fun with Textareas </title> <script type="text/javascript" src="verify.js"> </script> <script type="text/javascript"> function Table(low, high, power) {// Results: displays table of numbers between low & high, raised to power var message = "i: i^" + power + "\n \n"; for (var i = low; i <= high; i++) { message = message + i + ": " + Math.pow(i, power) + "\n"; } document.AreaForm.Output.value = message; </head> <body> <form name="AreaForm"> <div style="text-align: center;"> Show the numbers from <input type="text" name="lowRange" size=“4” value=“1” onchange="VerifyInt(this);" /> to <input type="text" name="highRange" size=“4” value=“10” onchange="VerifyInt(this);" /> raised to the power of <input type="text" name="power" size=3 value=2 <br /> <br /> <input type="button" value="Generate Table" onClick="Table(parseFloat(document.AreaForm.lowRange.value), parseFloat(document.AreaForm.highRange.value), parseFloat(document.AreaForm.power.value));" /> <textarea name="Output" rows=“20” cols=“15”></textarea> </div> </form> </body> </html> view page

18 JavaScript & Timeouts تابع setTimeout را می توان جهت اجرای کد در زمان های بعدی استفاده نمود. setTimeout(JavaScriptCodeToBeExecuted, MillisecondsUntilExecution) <html> <!– COMP519 form13.html > <head> <title> Fun with Timeouts </title> <script type="text/javascript"> function Move() // Results: sets the current page contents to be newhome.html { self.location.href = "form10.htm"; } </script> </head> <body onload="setTimeout('Move()', 3000);"> This page has moved to <a href=“form10.htm">newhome.html</a>. </body> </html> view page

19 Another Timeout Example
<html> <!–- COMP519 form14.html > <head> <title> Fun with Timeouts </title> <script type="text/javascript"> a=1000; function timeSince() // Assumes: document.CountForm.countdown exists in the page // Results: every second, recursively writes current countdown in the box { a--; document.CountForm.countdown.value=a; setTimeout("timeSince();", 1000); } </script> </head> <body onload="timeSince();"> <form name="CountForm"> <div style="text-align: center;"> Countdown to Graduation 2007 <br /> <textarea name="countdown" rows=“4” cols=“15” style="font-family: Courier;" onfocus="blur();"></textarea> </div> </form> </body> </html> view page

20 Cookies & JavaScript کلوچه ها فایل های داده ای هستند که روی ماشین کلاینت ذخیره می شوند. قابل دسترسی و تغییر توسط سرور هستند. می توان با JavaScript نیز آنها را تغییر داد یا باز کرد. موارد استفاده: تجارت الکترونیکی:یادگیری اسم مشتری، خریدهای قبلی، رمز عبور و ... خودآموز: ذخیره دروس یاد داده شده، نمرات و .... بازیها: ذخیره امتیازات قبلی هر صفحه میتواند کلوچه مخصوص به خود را داشته باشد. document.cookie مجموعه ای از زوجهای attribute=value است که با ; از هم جدا شده اند. "userName=Dave;score=100;expires=Mon, 21-Feb-01 00:00:01 GMT"

21 cookie.js function getCookie(Attribute)
// Assumes: Attribute is a string // Results: gets the value stored under the Attribute { if (document.cookie.indexOf(Attribute+"=") == -1) { return ""; } else { var begin = document.cookie.indexOf(Attribute+"=") + Attribute.length+1; var end = document.cookie.indexOf(";", begin); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(begin, end)); function setCookie(Attribute, Value) // Results: stores Value under the name Attribute, expires in 30 days var ExpireDate = new Date(); ExpireDate.setTime(ExpireDate.getTime() + (30*24*3600*1000)); document.cookie = Attribute + "=" + escape(Value) + "; expires=" + ExpireDate.toGMTString(); function delCookie(Attribute) // Results: removes the cookie value under the name Attribute var now = new Date(); document.cookie = Attribute + "=; expires=" + now.toGMTString();

22 Cookie Example view page <html>
<!– COMP519 form15.html > <head> <title> Fun with Cookies </title> <script type="text/javascript" src=" </script> <script type="text/javascript"> function Greeting() // Results: displays greeting using cookie { visitCount = getCookie("visits"); if (visitCount == "") { alert("Welcome to my page, newbie."); setCookie("visits", 1); } else { visitCount = parseFloat(visitCount)+1; alert("Welcome back for visit #" + visitCount); setCookie("visits", visitCount); </head> <body onload="Greeting();"> Here is the stuff in my page. <form name="ClearForm"> <div style="text-align: center;"> <input type="button" value="Clear Cookie" onclick="delCookie('visits');" /> </div> </form> </body> </html> view page

23 مقايسه جاوا و جاوااسکريپت
يادآوري: JavaScript براي انجام کارهاي ساده خوب است. GUI آساني دارد و سريع آماده مي شود. انواع داده اي آن انعطاف پذير هستند. براحتي با HTML ترکيب مي شود. پشتيباني کتابخانه اي زيادي ندارد و از ساختمان داده هاي محدودي استفاده ميکند. براي پروژههاي بزرگ و چند فايلي و OO مناسب نيست. يادآوري: جاوا براي انجام کارهاي پيچيده مخصوصا گرافيکي مناسب است. کامل است – توابع وکلاسهاي کتابخانه اي زيادي دارد. براي انجام پروژه هاي بزرگ مناسب است. GUI آن مشکلتر است. ترکيب جاوا و HTML واضح نيست. ايده آل: استفاده از تواناييهاي هر دو زبان استفاده از اپلتهاي جاوا در هنگام نياز ( مثل گرافيک) ايجاد ارتباط بين کد جاوا و JavaScript

24 Calling Java Routines from JavaScript
Netscape و اپرا اجازه دسترسي مستقيم به روتينهاي جاوا را مي دهند. يايد اسم کامل روتين را مشخص کنيد. ممکن است IE از اين خاصيت پشتيباني نکند. <html> <!-- COMP java.html > <!-- Note: works in Netscape/Firefox only. --> <head> <title>Java+JavaScript Demo</title> </head> <body> <script type=“text/javascript"> document.write(java.lang.Math.random()); </script> </body> </html> view page

25 Calling Applet Methods
معمولا ما مي خواهيم که يک اپلت را به صفحه الحاق کنيم و از طريق رخدادهاي HTML و JavaScript آن را کنترل کنيم. مثال: مي خواهيم تعدادي نقطه داخل يک مربع رسم کنيم.

26 MontePI import java.awt.*; import java.applet.*; import java.util.Random; public class Monte6 extends Applet { private static Random randy; private int SIZE; private Image offScreenImage; private Graphics offScreenGraphics; private int randomInRange(int low, int high) {…} private double distance(int x1, int y1, int x2, int y2) {…} public void init() randy = new Random(); Dimension dim = getSize(); SIZE = dim.width; drawCircle(); } public void drawCircle() { // DRAWS CIRCLE ON BOTH getGraphics() AND // offScreenGraphics public void drawDots(int numPoints) // DRAWS numPoints RANDOM DOTS ON BOTH getGraphics() // AND offScreenGraphics public void paint(Graphics g) g.drawImage(offScreenImage, 0, 0, null); init يک توليد کننده اعداد تصادفي ايجاد مي کند و اندازه اپلت را مي خواند. drawDots نقاط را داخل صفحه رسم می کند و در بافر می ریزد. paint با استفاده از بافر صفحه را دوباره رسم می کند.

27 MontePI (cont.) here, HTML button controls the applet (via JavaScript)
<!–- COMP Monte6.html > <head> <title>Monte Carlo Darts Page</title> <script type=“text/css”> body { background-color: gray; } </script> </head> <body> <div style="text-align: center;"> <applet code="Monte6.class" name="MonteApplet" height=“300” width=“300”> You must use a Java-enabled browser to view this applet. </applet> <p><br /><br /></p> <form name="MonteForm"> <input type="button" value="Generate points" onclick="document.MonteApplet.drawDots(500);“ /> </form> </div> </body> </html> here, HTML button controls the applet (via JavaScript) view page

28 Example (cont.) یک واسط بهتر:
<html> <!–- COM Monte6a.html > <head> <title>Monte Carlo Darts Page</title> <style type=“text/css”> body { background-color: gray; } </style> </head> <body style=“background-color: gray;"> <div style="text-align: center;"> <applet code="Monte6.class" name="MonteApplet" height=“300” width=“300”> You must use a Java-enabled browser to view this applet. </applet> <p><br /></p> <form name="MonteForm"> <input type="button" value="Generate" onClick="numDots = parseFloat(document.MonteForm.numPoints.value); document.MonteApplet.drawDots(numDots);“ /> <input type="text" name="numPoints" size=“6” value=“500” /> points <p><br /></p> <input type="button" value="Clear the screen" onclick="document.MonteApplet.drawCircle();“ /> </form> </div> </body> </html> یک واسط بهتر: می توان به کاربر اجازه داد که تعداد نقاط را مشخص کند. view page


Download ppt "Event-driven programs and HTML form elements"

Similar presentations


Ads by Google