Chọn phương thức add ()
Thí dụ
Thêm tùy chọn "Kiwi" vào cuối danh sách thả xuống:
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
Định nghĩa và Cách sử dụng
Phương thức add () được sử dụng để thêm một tùy chọn vào danh sách thả xuống.
Mẹo: Để xóa một tùy chọn khỏi danh sách thả xuống, hãy sử dụng phương thức remove () .
Hỗ trợ trình duyệt
Method | |||||
---|---|---|---|---|---|
add() | Yes | Yes | Yes | Yes | Yes |
Cú pháp
selectObject.add(option, index)
Giá trị tham số
Parameter | Description |
---|---|
option | Required. Specifies the option to add. Must be an option or optgroup element |
index | Optional. An integer that specifies the index position for where the new option element should be inserted. Index starts at 0. If no index is specified, the new option will be inserted at the end of the list |
Chi tiết kỹ thuật
Giá trị trả lại: | Không có giá trị trả lại |
---|
Các ví dụ khác
Thí dụ
Thêm tùy chọn "Kiwi" ở đầu danh sách thả xuống:
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option, x[0]);
Thí dụ
Thêm tùy chọn "Kiwi" ở vị trí chỉ mục "2" của danh sách thả xuống:
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option, x[2]);
Thí dụ
Thêm một tùy chọn trước một tùy chọn đã chọn trong danh sách thả xuống:
var x = document.getElementById("mySelect");
if (x.selectedIndex >= 0) {
var option = document.createElement("option");
option.text = "Kiwi";
var sel = x.options[x.selectedIndex];
x.add(option, sel);
}
❮ Chọn đối tượng