js code realizes simple form selection

 

 

Article directory

 


foreword

no foreword


Tip: The following is the text of this article, and the following cases are for reference

1. Demand

Realize unselect all, select all, inverse select

Two, js code

1. Rendering options

If there are several items in the array, several options will be rendered, and added to form1 after setting the style.

let input_arr;
        let p_arr=["Dior","Chanel","LV","YSL","Mac","TF"]
        let form2 = document.querySelector("#form2");
        let form1 = document.querySelector("#form1");

        function render() {
            for (let i = 0; i < p_arr.length; i++) {
                let input = document.createElement("input");
                let p=document.createElement("p");
                input.type = `checkbox`;
                input.style.marginRight=`15px`;
                p.innerHTML=`${p_arr[i]}`;
                form1.appendChild(p);
                form1.appendChild(input);
                input.style.marginTop=`20px`;
            }
           input_arr = document.querySelectorAll("[type='checkbox']");
        }
        render();

rendering options


2. Realize the function

Use event delegation to bind the monitor to form2, traverse the array, enter the corresponding branch, select all: if the option is not selected (false), then the checked value of the option is (true), that is, selected. Do not choose and reverse choose the same as above.

  form2.addEventListener("click", function () {
            for (let item of input_arr) {
                switch (event.target.id) {
                    case "all":
                        item.checked == false ? item.checked = true : "";
                        break;
                    case "all_none":
                        item.checked == true ? item.checked = false : "";
                        break;
                    case "reverse":
                        item.checked == true ? item.checked = false : item.checked = true;
                        break;
                }
            }
        })

select part


 

reverse election

unselect all

select all


Summarize

not difficult

Guess you like

Origin blog.csdn.net/huangyinzhang/article/details/108308285
Recommended