드롭 다운 상자에서 모든 옵션을 지우려면 어떻게합니까?
내 코드는 IE에서는 작동하지만 Safari, Firefox 및 Opera에서는 작동하지 않습니다. (큰 놀라움)
document.getElementById("DropList").options.length=0;
검색 한 후, length=0
그것이 마음에 들지 않는다는 것을 알게되었습니다 .
나는 해봤 ...options=null
과 var clear=0; ...length=clear
같은 결과.
한 번에 여러 객체 에이 작업을 수행하므로 경량 JS 코드를 찾고 있습니다.
다음을 사용하여 모든 요소를 지울 수 있습니다. 참고
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
select.options[i] = null;
}
선택한 html 객체의 옵션을 제거하려면 다음 코드를 사용하십시오.
function removeOptions(selectbox)
{
var i;
for(i = selectbox.options.length - 1 ; i >= 0 ; i--)
{
selectbox.remove(i);
}
}
//using the function:
removeOptions(document.getElementById("mySelectObject"));
이것은 모든 브라우저에서 작동합니다. =)
간단한 스크립트를 원한다면 jQuery로 가십시오. jQuery에서 모든 옵션을 제거하는 솔루션은 다음과 같습니다.
$("#droplist").empty();
아마도 가장 깨끗한 솔루션은 아니지만 하나씩 제거하는 것보다 훨씬 간단합니다.
document.getElementById("DropList").innerHTML = "";
이것이 가장 좋은 방법입니다.
function (comboBox) {
while (comboBox.options.length > 0) {
comboBox.remove(0);
}
}
가장 짧은 방법입니다.
document.getElementById('mySelect').innerText = null
한 줄, 아니요, JQuery 없음, 단순
function removeOptions(obj) {
while (obj.options.length) {
obj.remove(0);
}
}
이것은 약간 현대적이고 순수한 JavaScript입니다.
document.querySelectorAll('#selectId option').forEach(option => option.remove())
와 PrototypeJS :
$('yourSelect').select('option').invoke('remove');
JQuery를 사용하고 있고 선택 컨트롤에 ID "DropList"가있는 경우 다음과 같은 방법으로 옵션을 제거 할 수 있습니다.
$('#DropList option').remove();
실제로 그것은 datalist와 같은 옵션 목록으로 저에게 효과적입니다.
도움이 되길 바랍니다.
select는
-optgroup & -options
컬렉션
을 자식으로 가질 수 있습니다 .
그래서,
방법 # 1
var selectElement = document.getElementById('myselectid');
selectElement.innerHTML = '';
방법 # 2
var selectElement = document.getElementById('myselectid');
selectElement.textContent = '';
두 가지 모두 Chrome에서 작동합니다.
나는 더 단순하고 구식 인 방법 # 1을 좋아한다.
시험
document.getElementsByTagName("Option").length=0
또는 removeChild () 함수를 살펴보십시오.
또는 jQuery 프레임 워크를 사용하는 경우
$("DropList Option").each(function(){$(this).remove();});
원래 질문의 문제는 오늘날 더 이상 관련이 없다는 것을 지적하고 싶습니다. 그리고 그 솔루션의 버전이 더 짧습니다.
selectElement.length = 0;
I've tested that both versions work in Firefox 52, Chrome 49, Opera 36, Safari 5.1, IE 11, Edge 18, latest versions of Chrome, Firefox, Samsung Internet and UC Browser on Android, Safari on iPhone 6S, Android 4.2.2 stock browser. I think it is safe to conclude that it's absolutely compatible with whatever device there is right now, so I recommend this approach.
Using JQuery is a prettier, shorter & smarter way to do it!
$('#selection_box_id').empty();
Go reverse. Reason is size decreases after each remove.
for (i = (len-1); i > -1; i--) {
document.getElementById("elementId").remove(i);
}
This can be used to clear options:
function clearDropDown(){
var select = document.getElementById("DropList"),
length = select.options.length;
while(length--){
select.remove(length);
}
}
<select id="DropList" >
<option>option_1</option>
<option>option_2</option>
<option>option_3</option>
<option>option_4</option>
<option>option_5</option>
</select>
<button onclick="clearDropDown()">clear list</button>
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
select.options[i].remove();
}
Hope, this code will helps you
I think that is the best sol. is
$("#myselectid").html('');
The simplest solutions are the best, so You just need:
var list = document.getElementById('list');
while (list.firstChild) {
list.removeChild(list.firstChild);
}
<select id="list">
<option value="0">0</option>
<option value="1">1</option>
</select>
The items should be removed in reverse, otherwise it will cause an error. Also, I do not recommended simply setting the values to null
, as that may cause unexpected behaviour.
var select = document.getElementById("myselect");
for (var i = select.options.length - 1 ; i >= 0 ; i--)
select.remove(i);
Or if you prefer, you can make it a function:
function clearOptions(id)
{
var select = document.getElementById(id);
for (var i = select.options.length - 1 ; i >= 0 ; i--)
select.remove(i);
}
clearOptions("myselect");
var select = document.getElementById('/*id attribute of your select here*/');
for (var option in select){
select.remove(option);
}
Above answer's code need a slight change to remove the list complete, please check this piece of code.
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length;) {
select.options[i] = null;
length = select.options.length;
}
refresh the length and it will remove all the data from drop down list. Hope this will help someone.
while(document.getElementById("DropList").childNodes.length>0)
{
document.getElementById("DropList").removeChild(document.getElementById("DropList").childNodes[0]);
}
If you have to support IE and you have more than 100 items in your select list, I strongly recommend you consider replacing the select with a function like so:
function clearOptions(select) {
var selectParentNode = select.parentNode;
var newSelect = select.cloneNode(false); // Make a shallow copy
selectParentNode.replaceChild(newSelect, select);
return newSelect;
}
The select parameter should be the element either from a jquery selector or document.getElementBy call. The only downside to this is that you lose events you had wired up to the select, but you can easily reattach them as it is returned back out of the function. I was working with a select that had ~3k items and it would take 4 seconds on IE9 to clear the select so I could update it with the new content. Nearly instant doing it this way.
Today I was facing same problem, I did as below while reloading select box. (In Plain JS)
var select = document.getElementById("item");
select.options.length = 0;
var opt = document.createElement('option');
opt.value = 0;
opt.innerHTML = "Select Item ...";
opt.selected = "selected";
select.appendChild(opt);
for (var key in lands) {
var opt = document.createElement('option');
opt.value = lands[key].id;
opt.innerHTML = lands[key].surveyNo;
select.appendChild(opt);
}
var select =$('#selectbox').val();
참고URL : https://stackoverflow.com/questions/3364493/how-do-i-clear-all-options-in-a-dropdown-box
'Programming' 카테고리의 다른 글
UITextField의 커서를 숨 깁니다. (0) | 2020.07.10 |
---|---|
android 5에서 기본 대화 상자 텍스트 색상을 변경하는 방법 (0) | 2020.07.10 |
UITableView를 스크롤 할 때 키보드 숨기기 (0) | 2020.07.10 |
"헝가리어 표기법"을 사용해야하는 이유는 무엇입니까? (0) | 2020.07.10 |
IE9에서 Javascript에서 VBScript로 아무것도 전달하지 않음 (0) | 2020.07.10 |