GarGerry commited on
Commit
94367ea
·
verified ·
1 Parent(s): 9cd7849

Create script.js

Browse files
Files changed (1) hide show
  1. script.js +53 -0
script.js ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Menangani submit form untuk konversi mata uang
2
+ document.getElementById('currencyForm').addEventListener('submit', async function(event) {
3
+ event.preventDefault();
4
+
5
+ // Ambil nilai input dari user
6
+ const amount = document.getElementById('amount').value;
7
+ const fromCurrency = document.getElementById('fromCurrency').value;
8
+ const toCurrency = document.getElementById('toCurrency').value;
9
+ const resultDiv = document.getElementById('result');
10
+
11
+ // Validasi jumlah yang dimasukkan
12
+ if (!amount || amount <= 0) {
13
+ resultDiv.innerHTML = "Please enter a valid amount!";
14
+ return;
15
+ }
16
+
17
+ try {
18
+ const apiKey = '3ebe2ccf9eeea2aaef280201'; // API Key
19
+ const url = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/${fromCurrency}`;
20
+
21
+ // Mengambil data dari API
22
+ const response = await fetch(url);
23
+ const data = await response.json();
24
+
25
+ // Menangani respon API yang error
26
+ if (data.result === 'error') {
27
+ resultDiv.innerHTML = `Error: ${data['error-type']}`;
28
+ } else {
29
+ // Menyusun nilai konversi dan menampilkannya
30
+ const rate = data.conversion_rates[toCurrency];
31
+ const convertedAmount = (amount * rate).toFixed(2);
32
+ resultDiv.innerHTML = `${amount} ${fromCurrency} = ${convertedAmount} ${toCurrency}`;
33
+ }
34
+ } catch (error) {
35
+ resultDiv.innerHTML = "Error fetching conversion rate.";
36
+ console.error("Error:", error); // Menampilkan error di konsol
37
+ }
38
+ });
39
+
40
+ // Fungsi untuk menukar nilai dropdown
41
+ function swapCurrencies() {
42
+ const fromCurrency = document.getElementById("fromCurrency");
43
+ const toCurrency = document.getElementById("toCurrency");
44
+
45
+ // Tukar nilai antara dropdown
46
+ const temp = fromCurrency.value;
47
+ fromCurrency.value = toCurrency.value;
48
+ toCurrency.value = temp;
49
+
50
+ // Reset hasil konversi jika sudah ada
51
+ const resultDiv = document.getElementById('result');
52
+ resultDiv.innerHTML = ""; // Kosongkan hasil jika ada perubahan
53
+ }