Javascript : Function

Selasa, 26 Februari 2019

Javascript : Function


Fungsi / Function



Script :
<HTML>
<HEAD>
<TITLE>Contoh Fungsi</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
<!--
   function jumlah(x, y) {
      var hasil = x + y;
      return(hasil);
   }
   var z = jumlah(2, 3);
    document.write(z);
   document.write("<BR>");
   document.write(jumlah(4, 5));
//-->
</SCRIPT>
</BODY>
</HTML>

Hasil :



Script Function Rekursif: 
<HTML>
<HEAD>
<TITLE>Variabel Lokal</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
<!--
   function faktorial(n) {
      if (n == 0)
         return(1);
      else
         return( n * faktorial(n-1));
   }

   var z = 77;
   document.write("4! = " + faktorial(4));
//-->
</SCRIPT>
</BODY>
</HTML>


Hasil :


Script Function Lainnya :



<HTML>
<HEAD>
<TITLE>Validasi Masukan</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JavaScript">
<!--
   function cekNama(form) {
      if (form.elements[0].value == "") {
         alert("Nama harus dimasukkan");
         form.nama.focus();
         form.nama.select();
         return(false);
      }
      alert("Terima kasih, " +
            form.elements[0].value);    
      return(true);
   }
//-->
</SCRIPT>
<FORM NAME = "formku">
<PRE>
Nama : <INPUT TYPE = "TEXT" NAME = "nama"><BR>
<INPUT TYPE = "BUTTON" VALUE = "Kirim"
       onClick = "cekNama(this.form)"><BR>
</PRE>
</FORM>
</BODY>
</HTML>


Hasil :


Script :



<HTML>
<HEAD>
<TITLE>Jam</TITLE>
</HEAD>
<BODY>
<FORM NAME = "formWaktu">
Waktu Sekarang :
<INPUT TYPE = "TEXT"
       NAME = "teksWaktu"
       VALUE = ""
       SIZE = "22">
</FORM>
<SCRIPT LANGUAGE = "JavaScript">

   
function aturWaktu() {
      var sekarang = new Date();
      var waktuSekarang = sekarang.toLocaleString();
         document.formWaktu.teksWaktu.value =
          waktuSekarang;
      setTimeout('aturWaktu()', 1000);      
      return(true);
   }
   // Menjalankan fungsi aturWaktu
   aturWaktu();

</SCRIPT>
</BODY>
</HTML>


Hasil :



 

0 komentar :

Posting Komentar