JavaScript_ Add, delete and modify (add, delete and modify)

1, Requirement description

1. Add
After entering basic information (name, gender, age, city) through the input box, click the OK button to add an item of information to the table; Clicking reset will clear the information you entered.


2. Delete
Click the delete button after each item of information in the table, and click OK in the pop-up OK pop-up window to delete this item of information.


3. Modification
Click the Modify button after each item of information in the form, modify the information to be changed in the pop-up page, and click the OK button to complete the modification of the information in the form.


2, Complete code (including comments)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            border-collapse: collapse;
        }

        td {
            width: 100px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            border: 1px solid #000;
            font-size: 30px;
        }

        .change {
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            position: fixed;
            top: 0;
            left: 0;
        }

        .change>div {
            width: 300px;
            height: 300px;
            padding: 30px 15px;
            background: #fff;

        }
    </style>
</head>

<body>
    <div class="add">
        <p style="color: darkcyan; font-size: 25px;">newly added</p>
        full name: <input type="text" name="name"><br>
        Age: <input type="text" name="age"><br>
        Gender: male<input type="radio" name="sex" value="male">
        female<input type="radio" name="sex" value="female">
        secrecy<input type="radio" name="sex" value="secrecy"><br>
        city:
        <select name="city">
            <option value="0">Beijing</option>
            <option value="1">Shanghai</option>
            <option value="2">Guangzhou</option>
            <option value="3">Chongqing</option>
            <option value="4">Tianjin</option>
        </select> <br>
        <button>determine</button>
        <button type="reset">Reset</button>
    </div>

    <hr>

    <table>
        <thead>
            <tr>
                <td>Serial number</td>
                <td>full name</td>
                <td>Gender</td>
                <td>Age</td>
                <td>city</td>
                <td>delete</td>
                <td>modify</td>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <div class="change">
        <div>
            full name: <input type="text" name="name"><br>
            Age: <input type="text" name="age"><br>
            Gender: male<input type="radio" name="sex" value="male">
            female<input type="radio" name="sex" value="female">
            secrecy<input type="radio" name="sex" value="secrecy"><br>
            city:
            <select name="city">
                <option value="0">Beijing</option>
                <option value="1">Shanghai</option>
                <option value="2">Guangzhou</option>
                <option value="3">Chongqing</option>
                <option value="4">Tianjin</option>
            </select> <br>
            <button>determine</button>
            <button>cancel</button>
        </div>
    </div>

    <script>
        // Dynamically generate pages based on arrays
        const arr = [{
                id: 1,
                name: 'Zhang San',
                sex: 'male',
                age: 18,
                city: 'Beijing'
            },
            {
                id: 2,
                name: 'Li Si',
                sex: 'female',
                age: 19,
                city: 'Shanghai'
            },
            {
                id: 3,
                name: 'Wang Wu',
                sex: 'male',
                age: 20,
                city: 'Guangzhou'
            },
            {
                id: 4,
                name: 'Zhao Liu',
                sex: 'female',
                age: 21,
                city: 'Chongqing'
            },
            {
                id: 5,
                name: 'Liu Qi',
                sex: 'secrecy',
                age: 22,
                city: 'Tianjin'
            },
        ];
        // City array
        const cityArr = ['Beijing', 'Shanghai', 'Guangzhou', 'Chongqing', 'Tianjin'];
        // Get label object 
        const oTbody = document.querySelector('tbody');

        // Get new related label object
        const oAdd = document.querySelector('.add');
        // OK button
        const oBtnEnsure = oAdd.querySelectorAll('button')[0];
        // Reset button
        const oBtnReset = oAdd.querySelectorAll('button')[1];
        // full name
        const oIptName = oAdd.querySelector('[name="name"]');
        // Age
        const oIptAge = oAdd.querySelector('[name="age"]');
        // Gender
        const oIptSex = oAdd.querySelectorAll('[name="sex"]');
        // city
        const oSelCity = oAdd.querySelector('[name="city"]');

        // Get and modify related label objects
        const oChange = document.querySelector('.change');
        // OK button
        const oBtnEnsureChange = oChange.querySelectorAll('button')[0];
        // Cancel button
        const oBtnCancelChange = oChange.querySelectorAll('button')[1];
        // full name
        const oIptNameChange = oChange.querySelector('[name="name"]');
        // Age
        const oIptAgeChange = oChange.querySelector('[name="age"]');
        // Gender
        const oIptSexChange = oChange.querySelectorAll('[name="sex"]');
        // city
        const oSelCityChange = oChange.querySelector('[name="city"]');
        // City option
        const oOptChange = oChange.querySelectorAll('option');


        // Define a variable 
        // Stores the index subscript corresponding to the modified label 
        let index;
        // Call the function to dynamically render the generated page
        setPage();


        // Encapsulating functions to dynamically render and generate pages
        function setPage() {
            // The empty array generates the corresponding empty content
            if (arr.length === 0) {
                oTbody.innerHTML = '<tr><td colspan="7">No matching data</td></tr>';
                return;
            }
            let str = '';
            arr.forEach(function (item, key) {
                str += `
                    <tr>
                        <td>${item.id}</td>
                        <td>${item.name}</td>
                        <td>${item.sex}</td>
                        <td>${item.age}</td>
                        <td>${item.city}</td>
                        <td><button name="del" index="${key}">delete</button></td>
                        <td><button name="change" index="${key}">modify</button></td>
                    </tr>
                `;
            })
            oTbody.innerHTML = str;
        }


        // newly added
        // Add a click event to the OK button
        oBtnEnsure.addEventListener('click', function () {
            // Pop up the confirmation box, click OK, and then execute the program
            // That is, window The return value of confirm() is true, and then execute the program
            if (window.confirm('Are you sure you want to add?')) {
                // get data 
                // Get name
                let name = oIptName.value;
                console.log(name);
                // Get age converted to numeric type
                let age = oIptAge.value - 0;
                // Get city
                // Convert the values corresponding to the city into specific Chinese data through the array
                let city = cityArr[oSelCity.value];
                // Get gender
                let sex;
                for (let i = 0; i <= oIptSex.length - 1; i++) {
                    if (oIptSex[i].checked) {
                        sex = oIptSex[i].value;
                        break;
                    }
                }
                //Here, forEach can also be used, but forEach will loop from beginning to end. It is better to use the for loop. You can terminate the loop after finding that the conditions are met
                // oIptSex.forEach(function (item) {
                //     if (item.checked) {
                //         sex = item.value;
                //     }
                // })
                // The new id is the id value of the last data unit in the original data + 1 
                let id = arr[arr.length - 1].id + 1;
                // Generate an object and write the last bit of the array
                arr.push({
                    id: id,
                    name: name,
                    sex: sex,
                    age: age,
                    city: city
                })
                console.log(arr);
                // Call the function again to dynamically render and generate a new page
                setPage();
            }
        })
        // Add click event to reset button
        oBtnReset.addEventListener('click', function () {
            oIptName.value = '';
            oIptAge.value = '';
            for (let i = 0; i <= oIptSex.length - 1; i++) {
                oIptSex[i].checked = false;
            }
            oSelCity.value = 0;
        })


        // Add a click event to the < tbody > tag
        // Implement project requirements through event delegation
        oTbody.addEventListener('click', function (e) {
            // According to the different name s of e.target, judge what tag is clicked and execute different programs

            // Delete program
            if (e.target.getAttribute('name') === 'del') {
                // Pop up the confirmation box, click OK and then execute the deletion program
                if (!window.confirm('Are you sure you want to delete?')) {
                    return;
                }
                // Delete a cell in the array according to the index subscript stored by clicking the delete button
                arr.splice(Number(e.target.getAttribute('index')), 1);
                // Dynamically render the generated page based on the new array
                setPage();

                // Modify program
            } else if (e.target.getAttribute('name') === 'change') {
                // Let the modified div tag appear
                oChange.style.display = 'flex'; // An elastic box is used in css style, so display:flex is used here
                // Assign a value to the variable and store the index subscript corresponding to the modified label
                index = Number(e.target.getAttribute('index'));

                // Displays the original data to be modified
                // Name, age, direct assignment 
                oIptNameChange.value = arr[index].name;
                oIptAgeChange.value = arr[index].age;
                // Loop through the input pseudo array storing gender
                // If the value of any tag is the same as the key value of sex in the array object, checked is added. It is selected by default.
                for (let i = 0; i <= oIptSexChange.length - 1; i++) {
                    if (oIptSexChange[i].value === arr[index].sex) {
                        // Add the selected effect to the input tag of the corresponding gender
                        oIptSexChange[i].checked = true;
                        // Terminate cycle
                        break;
                    }
                }
                // Loop through city option pseudo array
                // The content of the Select > option tag is the same as the city data of the corresponding object in the array arr
                // Add a selection effect to the Select > option tag
                for (let i = 0; i <= oOptChange.length - 1; i++) {
                    if (oOptChange[i].innerHTML === arr[index].city) {
                        oOptChange[i].selected = true;
                    }
                }
            }
        })


        // Add a click event to the OK button in the modification page
        oBtnEnsureChange.addEventListener('click', function () {
            // Pop up the confirmation box, click OK and then execute the program
            if (window.confirm('Are you sure you want to modify it?')) {
                // Gets or modifies the data value in the tag
                // Get name
                let name = oIptNameChange.value;
                // Get age, convert to numeric type
                let age = oIptAgeChange.value - 0;
                // Get city
                // Through the array, the values corresponding to the city are transformed into specific Chinese data
                let city = cityArr[oSelCityChange.value];
                // Get gender
                let sex;
                for (let i = 0; i <= oIptSexChange.length - 1; i++) {
                    if (oIptSexChange[i].checked) {
                        sex = oIptSexChange[i].value;
                        break;
                    }
                }
                // Modify the data stored by the object in the array corresponding to the index subscript stored in the modified tab
                arr[index].name = name;
                arr[index].age = age;
                arr[index].sex = sex;
                arr[index].city = city;
                // Call the function to dynamically render the page according to the new array
                setPage();
                // Make the modified page hidden again
                oChange.style.display = 'none';
            }
        })
        // Add a click event to the modified cancel button
        oBtnCancelChange.addEventListener('click', function () {
            // Make the modified page hidden
            oChange.style.display = 'none';
        })
    </script>

</body>

</html>

3, Step summary

1. Define the function setPage() to dynamically render the generated page

1-1) since there is no database data at present, define an array to simulate the database data
1-2} define variables to store the final string content
1-3} loop through the array data and dynamically generate a string according to the data in the array
1-4) if there is no content in the array, you need to give corresponding prompt
1-5 # write string to label object

2. New click event

Add a new data unit to the array. The data unit must comply with the data structure in the array. The data in the object is stored in the form of key value pairs. It must comply with the form of key name storage in the original array. The page is dynamically rendered again according to the new array.
2-1} pop up the confirmation box, and confirm before adding
2-2} get the data in the tag object
2-3} define the data as an object and write it to the last bit of the array
2-4) call setPage() function again to dynamically render the generated page

3. Add click events to delete and modify tags in the form of event delegation

Delete:
3-1} pop up the confirmation box and confirm before deleting
3-2 , get the index index index stored in the clicked delete tag, and delete a data unit from the array according to this index index index
3-3} call the function to dynamically render the page again according to the new array

Modification:
3-1} let the modification page display
3-2 # store the global variable index and click the index subscript corresponding to the modify tab
3-3} assign the data stored in the corresponding object in the array to the tag in the modification page. name and age data stored in the two input direct assignment objects; Loop through the pseudo array of gender input tag. If the value of gender input tag is the same as the sex data stored in the corresponding object in the array, assign true to the checked attribute of this gender input tag, and then terminate the loop; Loop through the pseudo array of the city option tag. If the content of the city option tag is the same as the city data stored in the corresponding object in the array, assign a value of true to the selected attribute of the city option tag, and then terminate the loop

4. Click OK to modify and add a click event

Obtain the data input in the input tag, modify the data stored in the corresponding object unit in the array, and dynamically render the page according to the new array.
4-1} pop up the confirmation box and confirm before deleting
4-2} get the data stored in input, select and other tags
4-3 , modify the data value stored in the object unit obtained by the corresponding index index in the array according to the global variable index as the index index index
4-4} call the function setPage() to dynamically render the page content again according to the new array unit
4-5 # make the modified page hide and disappear

5. Click the Cancel button on the modified page to add a click event to hide and disappear the modified page.                                             

Keywords: Javascript html css

Added by danscreations on Thu, 09 Dec 2021 19:27:11 +0200