선택 상자의 모든 옵션을 제거한 다음 하나의 옵션을 추가하고 jQuery로 선택하려면 어떻게 해야 합니까?

StackOverflow https://stackoverflow.com/questions/47824

문제

핵심 jQuery를 사용하여 선택 상자의 모든 옵션을 제거한 다음 하나의 옵션을 추가하고 선택하는 방법은 무엇입니까?

내 선택 상자는 다음과 같습니다.

<Select id="mySelect" size="9" </Select>

편집하다:다음 코드는 연결에 도움이 되었습니다.하지만 (Internet Explorer에서는) .val('whatever') 추가된 옵션을 선택하지 않았습니다.(나는 두 가지 모두에서 동일한 '값'을 사용했습니다. .append 그리고 .val.)

$('#mySelect').find('option').remove().end().append('<option value="whatever">text</option>').val('whatever');

편집하다:이 코드를 모방하기 위해 페이지/양식이 재설정될 때마다 다음 코드를 사용합니다.이 선택 상자는 라디오 버튼 세트로 채워집니다. .focus() 더 가까웠지만 옵션이 다음과 같이 선택되어 표시되지 않았습니다. .selected= "true".기존 코드에는 아무런 문제가 없습니다. 단지 jQuery를 배우려고 할 뿐입니다.

var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";

편집하다:선택한 답변은 내가 필요한 답변에 가깝습니다.이것은 나에게 효과적이었습니다.

$('#mySelect').children().remove().end().append('<option selected value="whatever">text</option>') ;

그러나 두 답변 모두 최종 솔루션으로 이어졌습니다.

도움이 되었습니까?

해결책

$('#mySelect')
    .find('option')
    .remove()
    .end()
    .append('<option value="whatever">text</option>')
    .val('whatever')
;

다른 팁

$('#mySelect')
    .empty()
    .append('<option selected="selected" value="whatever">text</option>')
;

왜 일반 자바스크립트를 사용하지 않는 걸까요?

document.getElementById("selectID").options.length = 0;

위의 jQuery 메서드를 사용하면 IE7(IE6에서는 잘 작동)에 버그가 있었습니다. 선택하다 DOM에는 있지만 화면에는 없습니다.IE 개발자 도구 모음을 사용하여 다음을 확인할 수 있었습니다. 선택하다 모든 것이 지워지고 새 항목이 생겼지만 시각적으로 선택하다 선택할 수 없더라도 여전히 이전 항목이 표시되었습니다.

수정 사항은 jQuery 대신 표준 DOM 메서드/속성(포스터 원본과 동일)을 사용하여 지우는 것이었습니다. 여전히 jQuery를 사용하여 옵션을 추가했습니다.

$('#mySelect')[0].options.length = 0;

목표가 선택 항목에서 첫 번째 옵션(일반적으로 '항목을 선택하세요' 옵션)을 제외한 모든 옵션을 제거하는 것이라면 다음을 사용할 수 있습니다.

$('#mySelect').find('option:not(:first)').remove();

어쨌든 기본적으로 선택되므로 "하나를 추가하고 선택하십시오"라는 말이 정확히 무엇을 의미하는지 잘 모르겠습니다.그러나 둘 이상을 추가한다면 더 의미가 있을 것입니다.다음과 같은 것은 어떻습니까?

$('select').children().remove();
$('select').append('<option id="foo">foo</option>');
$('#foo').focus();

"EDIT"에 대한 응답:"이 선택 상자는 라디오 버튼 세트로 채워져 있습니다"라는 말의 의미를 명확히 할 수 있습니까?ㅏ <select> 요소는 (법적으로) 다음을 포함할 수 없습니다. <input type="radio"> 강요.

$('#mySelect')
    .empty()
    .append('<option value="whatever">text</option>')
    .find('option:first')
    .attr("selected","selected")
;
$("#control").html("<option selected=\"selected\">The Option...</option>");

받은 답변 덕분에 내 요구에 맞는 다음과 같은 것을 만들 수 있었습니다.내 질문은 다소 모호했습니다.후속 조치를 취해 주셔서 감사합니다.내 마지막 문제는 내가 선택하고 싶은 옵션에 "선택됨"을 포함시켜 해결되었습니다.

$(function() {
  $('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected
  $("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1
  // Bind click event to each radio button.
  $("input[name='myRadio']").bind("click",
                                  function() {
    switch(this.value) {
      case "1":
        $('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ;
        break ;
      case "2":
        $('#mySelect').find('option').remove() ;
        var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo
        var options = '' ;
        for (var i = 0; i < items.length; i++) {
          if (i==0) {
            options += '<option selected value="' + items[i] + '">' + items[i] + '</option>';
          }
          else {
            options += '<option value="' + items[i] + '">' + items[i] + '</option>';
          }
        }
        $('#mySelect').html(options);   // Populate select box with array
        break ;
    } // Switch end
  } // Bind function end
                                 ); // bind end
}); // Event listener end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>One<input  name="myRadio" type="radio" value="1"  /></label>
<label>Two<input name="myRadio"  type="radio" value="2" /></label>
<select id="mySelect" size="9"></select>

  1. 먼저 첫 번째 옵션을 제외한 기존 옵션을 모두 지웁니다(--선택--)

  2. 루프를 사용하여 하나씩 새 옵션 값을 추가합니다.

    $('#ddlCustomer').find('option:not(:first)').remove();
    for (var i = 0; i < oResult.length; i++) {
       $("#ddlCustomer").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID));
    }
    

HTML을 새 데이터로 변경하는 것은 어떻습니까?

$('#mySelect').html('<option value="whatever">text</option>');

다른 예시:

$('#mySelect').html('
    <option value="1" selected>text1</option>
    <option value="2">text2</option>
    <option value="3" disabled>text3</option>
');

또 다른 방법:

$('#select').empty().append($('<option>').text('---------').attr('value',''));

이 링크에는 모범 사례가 있습니다. https://api.jquery.com/select/

인터넷에서 아래와 같은 내용을 찾았습니다.내 상황과 같은 수천 가지 옵션을 사용하면 이것이 것보다 훨씬 빠릅니다. .empty() 또는 .find().remove() jQuery에서.

var ClearOptionsFast = function(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;
}

더 많은 정보 여기.

mauretto의 답변을 바탕으로 읽고 이해하기가 조금 더 쉽습니다.

$('#mySelect').find('option').not(':first').remove();

특정 값을 가진 옵션을 제외한 모든 옵션을 제거하려면 다음을 사용할 수 있습니다.

$('#mySelect').find('option').not('[value=123]').remove();

추가할 옵션이 이미 있으면 더 좋을 것입니다.

$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');

옵션 찾기 기준이 언급되지 않았으므로 코드의 첫 번째 줄은 선택 상자의 모든 옵션을 제거합니다.

코드의 두 번째 줄은 지정된 값("testValue") 및 Text("TestText")를 사용하여 옵션을 추가합니다.

제이쿼리를 사용합니다 소품() 선택한 옵션을 지우려면

$('#mySelect option:selected').prop('selected', false);

그러면 기존 mySelect가 새로운 mySelect로 대체됩니다.

$('#mySelect').replaceWith('<Select id="mySelect" size="9">
   <option value="whatever" selected="selected" >text</option>
   </Select>');

html을 교체하면 간단히 할 수 있습니다

$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');

그것이 효과가 있기를 바랍니다

$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
  • 개체에 추가할 옵션 값을 저장합니다.
  • 선택 태그에서 기존 옵션 지우기
  • 목록 개체를 반복하고 원하는 선택 태그에 내용을 추가합니다.

var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};

$('#selectID').empty();

$.each(listToAppend, function(val, text) {
    $('#selectID').append( new Option(text,val) );
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

select2에서 이 코드를 봤습니다.https://select2.org/programmatic-control/add-select-clear-items#clearing-selections

$('#mySelect).val(null).trigger('change');
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
    var d = data[i];
    var option = $('<option/>').val(d.id).text(d.title);
    select.append(option);
}
select.val('');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top