Passing Form Data and Elements to Functions

calendar September 20, 2009

Javascript features a keyword this that always refers to object contains the script in which the keyword is used.

<input type=”text” name=”textfield” onchange=”myfunction(this)” /> the keyword this pass a reference of the text object to the function.

<input type=”button” value=”click” onclick=”myfunction(this.form)” /> a reference to the entire form, rather than just the object calling the function.

Code:

<html>
 <head>
 <title>Beatle picker</title>
 <script type="text/javascript">
//---------------------------------------------------------------------
 function myfunction_A(form)
 {
   for(var i=0; i<form.Beatles.length; i++)
   {
     if(form.Beatles[i].checked)
     break;
   }
   var beatle = form.Beatles[i].value;
   var song = form.song.value;
   alert(song + " " + beatle);
 }
//--------------------------------------------------------------------
 function myfunction_B(entry)
 {
   var song = entry.value;
   alert(song);
 }
//--------------------------------------------------------------------
 </script>
 </head>
 <body>
 <p>
 <form onsubmit="return false">
 <input type="radio" name="Beatles" value="John Lennon" checked />John
 <input type="radio" name="Beatles" value="Paul McCartney" />Paul
 <input type="radio" name="Beatles" value="George Harrison" />George
 <input type="radio" name="Beatles" value="Ringo Star" />Ringo
 </p>
<p>
 <input type="text" name="song" value="Eleanor Rigby" onchange="myfunction_B(this)"/>
 <input type="submit" name="process" value="Process" onclick="myfunction_A(this.form)" />
 </p>
 </form>
 </body>
 </html>
admin

Leave a Reply

You must be logged in to post a comment.