module 7

 PROJECT 7.2


Saya akan membuat sebuah program javascript dengan hasil seperti gambar berikut:


dengan ketentuan seperti berikut:

• 1. Modifikasi table buah pada Mini Project sebelumnya • 

2. Jika button edit diklik maka input edit langsung muncul pada baris tersebut dan tombol edit berubah menjadi save (perhatikan gambar berikut)

 • 3. Ketika button save diklik maka, baris tersebut menjadi normal kembali yaitu berupa text dan gambar, tetapi dengan menggunakan nilai yang baru sesui hasil edit. Dan button save kembali menjadi edit


langsung kita mulai saja:


1. berikut kode HTML nya :

    <form id="dataForm">
        <label for="itemName">Nama Buah:</label>
        <input type="text" id="itemName" name="itemName" style="margin-left: 11px;">
    <br>
        <label for="itemWeight">Berat:</label>
        <input type="number" id="itemWeight" name="itemWeight" min="0" required style="margin-left: 52px;">
        <br>
        <label for="itemImage">URL Gambar:</label>
        <input type="text" id="itemImage" name="itemImage" ">
        <br>
        <button type="button" onclick="addData()">Tambah Data</button>
    </form>
   
    <!-- Table untuk memperlihatkan  data -->
    <table id="dataTable">
        <thead>
            <tr>
                <th>No</th>
                <th>Nama Buah</th>
                <th>Berat (kg)</th>
                <th>Gambar</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <!-- Data akan ditambahkan di sini -->
        </tbody>
    </table>


Dan berikut ini adalah kode CSS nya:

    <style>
        table {
            border-collapse: separate;
            width: 80%;
            margin: 20px auto;
        }

        th, td {
            border: 1px solid black;
            padding: 8px;
            text-align: left;
        }

        tr.red-bg td:nth-child(3) {
            background-color: red;
        }

        #dataForm {
           
            margin-top: 20px;

        }

        img {
            max-width: 50px;
            max-height: 50px;
        }

        .edit-input {
            width: 100%;
        }
    </style>


Dan yang terakhir ini adalah kode JAVACRIPTNYA :

<script>
        var editMode = false;
        var editedRow;

        function addData() {
            if (editMode) {
                // Update existing row in edit mode
                updateRow();
            } else {
                // Add new row in add mode
                var itemName = document.getElementById('itemName').value;
                var itemWeight = parseInt(document.getElementById('itemWeight').value);
                var itemImage = document.getElementById('itemImage').value;

                var tableBody = document.querySelector('#dataTable tbody');
                var newRow = document.createElement('tr');
                var rowCount = tableBody.rows.length + 1;

                newRow.innerHTML = '<td>' + rowCount + '</td>' +
                                   '<td><span contenteditable="true">' + itemName + '</span></td>' +
                                   '<td><span contenteditable="true">' + itemWeight + '</span></td>' +
                                   '<td><img src="' + itemImage + '" alt="Gambar Buah" style="max-width: 50px; max-height: 50px;"></td>' +
                                   '<td><button type="button" onclick="saveRow(this)">Save</button>' +
                                   ' <button type="button" onclick="deleteRow(this)">Hapus</button>' +
                                   ' <button type="button" onclick="editRow(this)">Edit</button></td>';

                // Apply red background if weight is more than 5 kg
                if (itemWeight > 5) {
                    newRow.classList.add('red-bg');
                }

                tableBody.appendChild(newRow);
                clearForm();
            }
        }

        function editRow(button) {
            editMode = true;
            editedRow = button.parentNode.parentNode;

            // Change button text to "Update"
            document.querySelector('#dataForm button').textContent = 'Update';

            // Replace content with input fields for inline editing
            for (var i = 1; i < editedRow.cells.length - 1; i++) {
                var cellContent = editedRow.cells[i].textContent;
                if (i !== 3) {
                    editedRow.cells[i].innerHTML = '<input class="edit-input" type="text" value="' + cellContent + '">';
                } else {
                    // Handle image separately
                    editedRow.cells[i].innerHTML = '<input class="edit-input" type="text" value="' + cellContent + '">' +
                                                    '<img src="' + cellContent + '" alt="Gambar Buah" style="max-width: 50px; max-height: 50px;">';
                }
            }
        }

        function updateRow() {
            // Reset edit mode, change button text, and clear form
            editMode = false;
            document.querySelector('#dataForm button').textContent = 'Tambah Data';

            // Update row with edited values
            var inputs = editedRow.querySelectorAll('.edit-input');
            for (var i = 0; i < inputs.length; i++) {
                if (i !== 2) {
                    editedRow.cells[i + 1].innerHTML = inputs[i].value;
                } else {
                    // Handle image separately
                    editedRow.cells[i + 1].innerHTML = '<img src="' + inputs[i].value + '" alt="Gambar Buah" style="max-width: 50px; max-height: 50px;">';
                }
            }

            clearForm();
        }

        function deleteRow(button) {
            var row = button.parentNode.parentNode;
            row.parentNode.removeChild(row);
            clearForm();
        }

        function saveRow(button) {
            if (editMode) {
                updateRow();
            } else {
                addData();
            }
        }

        function clearForm() {
            // Clear form values
            document.getElementById('itemName').value = '';
            document.getElementById('itemWeight').value = '';
            document.getElementById('itemImage').value = '';
        }
    </script>


Dan ini adalah hsilnya:




MODULE 7.3


 Saya akan membuat sebuah program javascript dengan hasil seperti gambar berikut:



 

dengan ketentuan seperti berikut


• Modifikasi Quiz 2 Exam Generator
 • Fields option hanya terdiri dari 1 field. 
• Semua opsi digabung dan dipisahkan menggunakan tanda koma.
 • Kolum Time pada table juga digabung menjadi satu.

berikut ini kode nya:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam Generator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 60%;
            margin: 50px auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input {
            width: calc(100% - 22px);
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .form-group input[type="number"] {
            width: 60px;
        }
        .form-group span {
            margin-left: 10px;
        }
        button {
            display: block;
            width: 100%;
            padding: 10px;
            background-color: #28a745;
            color: #fff;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
        }
        button:hover {
            background-color: #218838;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 15px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .options-table {
            width: 100%;
            margin-top: 10px;
        }
        .options-table td {
            padding: 10px;
        }
        .timer {
            text-align: right;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Exam Generator</h1>
        <div class="form-group">
            <label for="question">Question</label>
            <input type="text" id="question" placeholder="Enter your question">
        </div>
        <div class="form-group">
            <label for="option1">Option 1</label>
            <input type="text" id="option1" placeholder="Enter option 1">
        </div>
        <div class="form-group">
            <label for="option2">Option 2</label>
            <input type="text" id="option2" placeholder="Enter option 2">
        </div>
        <div class="form-group">
            <label for="option3">Option 3</label>
            <input type="text" id="option3" placeholder="Enter option 3">
        </div>
        <div class="form-group">
            <label for="option4">Option 4</label>
            <input type="text" id="option4" placeholder="Enter option 4">
        </div>
        <div class="form-group">
            <label for="time">Time</label>
            <input type="number" id="time" placeholder="Enter time in minutes">
            <span>Minutes</span>
        </div>
        <button onclick="addQuestionAndGenerateExam()">Add Question and Generate Exam</button>
        <table id="examTable">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Question</th>
                    <th>Options</th>
                    <th>Time</th>
                </tr>
            </thead>
            <tbody id="examBody">
            </tbody>
        </table>
    </div>
    <script>
        let questions = [];

        function addQuestionAndGenerateExam() {
            const question = document.getElementById('question').value.trim();
            const options = [
                document.getElementById('option1').value.trim(),
                document.getElementById('option2').value.trim(),
                document.getElementById('option3').value.trim(),
                document.getElementById('option4').value.trim()
            ];
            const time = parseInt(document.getElementById('time').value.trim());

            if (question && options.every(opt => opt) && !isNaN(time) && time > 0) {
                questions.push({ question, options, time });
                document.getElementById('question').value = '';
                document.getElementById('option1').value = '';
                document.getElementById('option2').value = '';
                document.getElementById('option3').value = '';
                document.getElementById('option4').value = '';
                document.getElementById('time').value = '';
                generateExam();
            } else {
                alert('Please fill out all fields correctly.');
            }
        }

        function generateExam() {
            const examBody = document.getElementById('examBody');
            examBody.innerHTML = '';
            questions.forEach((q, index) => {
                const timeInSeconds = q.time * 60;
                let timeLeft = timeInSeconds;

                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${index + 1}</td>
                    <td>${q.question}</td>
                    <td>
                        <table class="options-table">
                            <tr>
                                ${q.options.map((option, idx) => `
                                    <td>
                                        <input type="radio" id="option${index}${idx}" name="options${index}" value="${option}">
                                        <label for="option${index}${idx}">${String.fromCharCode(65 + idx)}. ${option}</label>
                                    </td>
                                `).join('')}
                            </tr>
                        </table>
                    </td>
                    <td class="timer" id="timer${index}">${Math.floor(timeLeft / 60)}:${(timeLeft % 60).toString().padStart(2, '0')}</td>
                `;
                examBody.appendChild(row);

                const countdownTimer = setInterval(() => {
                    if (timeLeft <= 0) {
                        clearInterval(countdownTimer);
                        document.getElementById(`timer${index}`).innerHTML = "Time's up!";
                    } else {
                        timeLeft--;
                        const minutes = Math.floor(timeLeft / 60);
                        const seconds = timeLeft % 60;
                        document.getElementById(`timer${index}`).innerHTML = `${minutes}:${seconds.toString().padStart(2, '0')}`;
                    }
                }, 1000);
            });
        }
    </script>
</body>
</html>

 

Dan ini adalah hsilnya:




SEE YOU in the nexr project 





Komentar

Postingan populer dari blog ini

Pemrograman berorientasi objek

Data Analytic