An option can be added to a select element using 3 approaches in jQuery:Method 1: Append the option tag khổng lồ the select boxThe option khổng lồ be added is created lượt thích a normal HTML string. The select box is selected with the jQuery selector và this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection. Hence the option is added to the select element.
Bạn đang xem: Add, select, or clear itemsSyntax:$("#selectBox").append(`$optionText`)Example:
Output:Before clicking the button:After clicking the button:Method 2: Using the Option() constructor lớn create a new optionThe Option() constructor is used to create a new option element. A new option is created with the text và the value of the option as the parameters. This element is then added lớn the select box with the append() method.
Output:Before clicking the button:After clicking the button:Method 3: Creating a new option element with the value và the textA new jQuery DOM element is created with the option tag. The value of the tag is set with the val() method and the text of the option is phối with the text() method. The element created is then added lớn the select box with the append() method.Syntax:$("#selectBox").append($("").val(optionValue).text(optionText))Example:
How to change the background màu sắc of the active nav-item?jQuery | attr() MethodHow khổng lồ prevent toàn thân from scrolling when a modal is opened using jQuery ?How to showroom `style=display:“block”` khổng lồ an element using jQuery?jQuery | children() with Examples