Get the App
SLTechnology News&Howtos  ›  Development  › 

The method of dynamic Operation of select drop-down Box by JavaScript

Shulou Source: shulou.com Published: 2022-06-01 00:07:35 09月19日 Update

This article introduces the relevant knowledge of "JavaScript dynamic operation of select drop-down box". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

First of all, there is our old friend "select" tag, because we need js and jq operations, so we define two select tags.

HTML code: after adding, you will refer to jq and define js and jq operations. I have pasted the code below.

JS Code:

/ / 1. Dynamic operation-JS mode / / define a json object here first Used to obtain and add to the select tag let language= {"languageList": [{"groupName": "front end", "optionName": [{"languageName": "html"}, {"languageName": "CSS"} {"languageName": "javascript"}],}, {"groupName": "backend", "optionName": [{"languageName": "java"} {"languageName": "JSP"}]}]} / / language.languageList-data location let index=0; for (obj of language.languageList) {/ / js create optgroup tag let optgroup=document.createElement ("optgroup"); / / set the label and id values of the optgroup tag optgroup.label=obj.groupName; optgroup.id= "optgroupId" + index / / add the creation optgroup to document.getElementById ("mySelect1") .add (optgroup) under select; / / add its option tag for (var I = 0; I < obj.optionName.length) for the optgroup tag Option +) {/ / js create the option tag let option=document.createElement ("option"); option.value= obj.optionName [I] .accounageName; option[ XSS _ name] = obj.optionName [I] .uploageName; document.getElementById ("optgroupId" + index) .appendChild (option) } index+=1; / / Custom subscript is added at the end to prevent id from increasing} / / 2 when adding option. Dynamically add-JQ mode let item=0; $("# addSelect2") .click (function () {item=item+1; / / jq click on the button and add the optgroup tag $("# mySelect2") .append ("); let r=Math.floor ((Math.random () * 5) + 1) in the drop-down box) / / generate random numbers 1-5 / / add a random number of option to the for under the newly added optgroup (var I = 1; I

Tags: Tags dynamic buttons code that is generation method drop-down content data way more knowledge random number practical learned and then subscript two number. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Apple NVidia Shulou Information Redmi