JavaScript xóa tất cả các tùy chọn đã chọn

Trong bài viết này, tôi sẽ giải thích bằng một ví dụ, cách xóa/xóa/xóa tất cả các mục (tùy chọn) khỏi DropDownList (DropDown) bằng JavaScript và jQuery

 

 

Xóa/Xóa/Xóa tất cả các mục (Tùy chọn) khỏi DropDownList bằng JavaScript

Đánh dấu HTML sau bao gồm một điều khiển DropDownList và một Nút

Khi Nút được nhấp, trình xử lý sự kiện nhấp chuột jQuery được thực thi. Bên trong trình xử lý sự kiện này, tất cả các mục (tùy chọn) của điều khiển DropDownList đều bị xóa (xóa) bằng hàm xóa jQuery

jQuery. Xóa tất cả các tùy chọn của một hộp chọn, sau đó thêm một tùy chọn và chọn nóCập nhật lần cuối vào ngày 19 tháng 8 năm 2022 21. 51. 35 (UTC/GMT +8 giờ)

jQuery Bài tập thực hành Phần I. Bài tập-15

Sử dụng jQuery xóa tất cả các tùy chọn của hộp chọn, sau đó thêm một tùy chọn và chọn nó

Giải pháp mẫu

Mã HTML


  
  
  
  
  
  Remove all the options of a select box and then add one option and select it with jQuery
  
  
  

  
  

Mã JavaScript

function Remove_options()
{
$('#myColor')
    .empty()
    .append('');
}

Xem Bút jquery-practical-exercise-15 của w3resource (@w3resource) trên CodePen


Đóng góp mã và nhận xét của bạn thông qua Disqus

Trước. Thêm phần tử danh sách trong phần tử danh sách không có thứ tự bằng jQuery
Kế tiếp. Gạch chân tất cả các từ trong văn bản bằng jQuery

Mức độ khó của bài tập này là gì?

Dễ dàng trung bình khó

Kiểm tra kỹ năng Lập trình của bạn với bài kiểm tra của w3resource



Theo dõi chúng tôi trên FacebookTwitter để cập nhật thông tin mới nhất.


  • Xu hướng hàng tuần
  • Bài tập lập trình Java cơ bản
  • Truy vấn con SQL
  • Bài tập cơ sở dữ liệu Adventureworks
  • Bài tập cơ bản C# Sharp
  • SQL COUNT() với sự khác biệt
  • Bài tập chuỗi JavaScript
  • Xác thực biểu mẫu HTML JavaScript
  • Bài tập bộ sưu tập Java
  • hàm SQL COUNT()
  • Tham gia bên trong SQL
  • Hàm JavaScript Bài tập
  • Hướng dẫn Python
  • Bài tập mảng Python
  • Tham gia chéo SQL
  • Bài tập về mảng Sharp trong C#


Sử dụng chức năng Javascript bên dưới để nhanh chóng xóa hoặc xóa tất cả các mục khỏi hộp chọn/danh sách thả xuống trong trang web của bạn

Mã nguồn

Các chức năng Javascript sau đây được cấp cho miền công cộng. Đọc bên dưới để biết cách triển khai các chức năng này

// Standard javascript function to clear all the options in an HTML select element
// In this method, you provide the id of the select dropdown box
function ClearOptions(id)
{
	document.getElementById(id).options.length = 0;
}

// Standard javascript function to clear all the options in an HTML select element
// In this method, you just provide the form name and dropdown box name
function ClearOptionsAlt(FormName, SelectName)
{
	document.forms[FormName].elements[SelectName].options.length = 0;
}

// Fast javascript function to clear all the options in an HTML select element
// Provide the id of the select element
// References to the old  object will become invalidated!
// This function returns a reference to the new select object.
function ClearOptionsFast(id)
{
	var selectObj = document.getElementById(id);
	var selectParentNode = selectObj.parentNode;
	var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
	selectParentNode.replaceChild(newSelectObj, selectObj);
	return newSelectObj;
}

// This is an alternative, simpler method.  Thanks to Victor T.
// It does not appear to be as fast as the ClearOptionsFast method in FF 3.6.
function ClearOptionsFastAlt(id)
{
	document.getElementById(id).innerHTML = "";
}




Example of Removing Options From a Drop-Down List




	Dropdown List
	


	Test Buttons
	



	Timing Results
	




How To Remove Options

Simple

The standard way to clear all the options is to simply set the options.length property to zero.  That function is listed below, and is fast enough when there are not that many options in the drop-down list (a.k.a. select boxes).  This method is also the most browser-compatible.  By clicking the the ‘add options’ and ‘remove options’ button above, you can see the required processing time in milliseconds.

Wrong

There are many sample codes on the Internet that loop through all the options in a for loop. Each option is removed one at a time with a call to remove or by setting them to null.  This is unnecessary at best, and slow and inefficient at best.  The simple method requires fewer lines of code and runs faster.

Fast Method

The problem comes when you have 1000s of options in the drop-down list.  Many browsers use 100% CPU and hang when removing that many options from a drop-down list.  This is most likely not due to the Javascript speed, but an operating system limitation.  This operation sometimes appears to be O(n^2), i.e. taking exponentially more time as the number of options increases.

I tried and timed various methods, such as hiding/showing and disabling/enabling the drop-down list.  Finally, I came up the idea of removing the drop-down list completely, and adding back an empty copy of the original one.  This is possible with calls to cloneNode and replaceChild on the document object.  The removed HTMLSelectElement (with all it’s options) is simply discarded, and the memory is freed by the browser when doing garbage collection.  A new one is shallow cloned from the old one, and inserted back into the page.  This is a O(1) or constant time operation.  The deletion is offloaded into the browser’s back-end garbage collection thread, which allows the UI to continue operating at full-speed.  The function is suitable for very large select boxes.

You can test this in your browser by adding 1000 or more options above, and then clicking one of the remove buttons.  Note, if you add too many options, your browser may hang for awhile.  The fast function is incorporated into this widget, Javascript Autocomplete Combobox and Search Widget, and is called after using the ‘load all matches’ button.

In IE 6, the standard method has the annoying effect of scrolling through the options while they are being erased.  The fast method avoids this.

The alternate fast method was provided by Victor T., and it has not been tested in all browsers, but seems to work well and be simpler.

Caveats

References to the original SELECT object will become invalidated!  If you had created references to the select object in your code, make sure to re-initialize those references again after calling the function.  This is because the function will destroy the original SELECT object.  The function returns a reference to the new SELECT object.

You should set a fixed width, so that the list does not annoyingly change size as options are added and removed.  An example is below.




	


ghi chú

Bạn có ước mình có thể nối nguyên mẫu hàm trên của phần tử HTMLSelectElement không? . Đoạn mã trên đã được thử nghiệm trong IE6, FireFox 3 và Opera 9. 1

Làm cách nào để xóa tất cả các tùy chọn chọn trong JavaScript?

Chúng ta chọn tất cả các tùy chọn trong hộp chọn bằng phương thức find() với tham số là “option“. Sau đó, chúng tôi xóa tất cả các tùy chọn đã chọn bằng cách sử dụng phương thức remove() . Chúng tôi sử dụng phương thức end() để hoàn nguyên lựa chọn trở lại hộp chọn. Để thêm một tùy chọn, có thể sử dụng phương thức append().

Làm cách nào để xóa lựa chọn thả xuống trong JavaScript?

Bằng cách nhấp vào biểu tượng xóa được hiển thị trong phần tử DropDownList , bạn có thể xóa mục đã chọn trong DropDownList thông qua tương tác. Bằng cách sử dụng thuộc tính showClearButton, bạn có thể bật biểu tượng rõ ràng trong phần tử DropDownList.

Làm cách nào để thêm và xóa các tùy chọn trong phần chọn bằng JavaScript?

JavaScript sử dụng loại HTMLSelectElement để đại diện cho phần tử Sử dụng phương thức add() của HTMLSelectElement để thêm tùy chọn vào phần tử Sử dụng phương thức remove() của HTMLSelectElement để xóa tùy chọn khỏi phần tử .

Làm cách nào để xóa tất cả các tùy chọn đã chọn ngoại trừ một tùy chọn trong jQuery?

Nếu chúng tôi muốn xóa tất cả các mục khỏi danh sách thả xuống ngoại trừ mục đầu tiên thì chúng tôi có thể sử dụng tùy chọn $('#ddlItems. không phải(. đầu tiên)'). remove(); Ở đây chúng tôi đã loại trừ mục đầu tiên khỏi bị xóa. Nếu chúng tôi muốn xóa tất cả các mục khỏi danh sách thả xuống ngoại trừ mục cuối cùng thì chúng tôi có thể sử dụng tùy chọn $('#ddlItems. không phải(. Cuối cùng)').