programing

jQuery를 사용하여 드롭다운의 선택한 인덱스 설정

mailnote 2023. 8. 4. 23:14
반응형

jQuery를 사용하여 드롭다운의 선택한 인덱스 설정

컨트롤을 찾는 방법이 다음과 같은 경우 jQuery에서 드롭다운 인덱스를 설정하는 방법은 무엇입니까?

$("*[id$='" + originalId + "']") 

동적으로 컨트롤을 만들고 웹 양식을 사용할 때 ID가 변경되므로 이 방법을 사용하여 컨트롤을 찾을 수 있습니다.그러나 일단 jQuery 개체를 갖게 되면 선택한 인덱스를 0(0)으로 설정하는 방법을 알 수 없습니다.

우선, 그 선택기는 꽤 느립니다.ID를 찾는 모든 DOM 요소를 검색합니다.요소에 클래스를 할당할 수 있으면 성능이 저하됩니다.

$(".myselect")

하지만 당신의 질문에 대답하기 위해, jQuery에서 요소 선택 값을 변경하는 몇 가지 방법이 있습니다.

// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0'); 

// sets selected index of a select box to the option with the value ""
$("select#elem").val(''); 

// sets selected index to first item using the DOM
$("select#elem")[0].selectedIndex = 0;

// sets selected index to first item using jQuery (can work on multiple elements)
$("select#elem").prop('selectedIndex', 0);

방금 이것을 발견했습니다. 저에게 효과가 있고 저는 개인적으로 읽기가 더 쉽다는 것을 알게 되었습니다.

이렇게 하면 gnarf의 답변 3번 옵션처럼 실제 인덱스가 설정됩니다.

// sets selected index of a select box the actual index of 0 
$("select#elem").attr('selectedIndex', 0);

예전엔 안 먹혔지만 지금은...버그 참조: http://dev.jquery.com/ticket/1474

부록

설명에서 권장하는 대로 다음을 사용합니다.

$("select#elem").prop('selectedIndex', 0);

저는 2015년에 이 답변을 작성하고 있는데, 어떤 이유로든 (아마도 이전 버전의 jQuery) 다른 답변은 저에게 효과가 없었습니다.제 말은, 그들은 선택된 인덱스를 변경하지만, 실제로는 실제 드롭다운에 반영되지 않습니다.

인덱스를 변경하고 드롭다운에 반영할 수 있는 또 다른 방법이 있습니다.

$('#mydropdown').val('first').change();

JQuery 코드:

$("#sel_status").prop('selectedIndex',1);

Jsp 코드:

Status:
<select name="sel_status"
    id="sel_status">
    <option value="1">-Status-</option>
    <option>ALL</option>
    <option>SENT</option>
    <option>RECEIVED</option>
    <option>DEACTIVE</option>
</select>

사용 중

$('#elem').val('xyz');

값이 ='xyz'인 옵션 요소를 선택합니다.

선택 요소에서 첫 번째 옵션의 값을 가져오려고 합니다.

$("*[id$='" + originalId + "']").val($("*[id$='" + originalId + "'] option:first").attr('value'));

두 번째 옵션 선택

$('#your-select-box-id :nth-child(2)').prop('selected', true);

여기에 '트리거'('변경')를 추가하여 이벤트를 발생시킵니다.

$('#your-select-box-id :nth-child(2)').prop('selected', true).trigger('change');

이것은 크롬과 인터넷 익스플로러에서도 제대로 작동합니다.

$("#MainContent_cmbEvalStatus").prop("selectedIndex", 1).change();

선택한 DropDown 0,1,2,3,4...의 위치 값을 입력합니다.

$("[id$='" + originalId + "']").val("0 index value");

0으로 설정합니다.

4번째 옵션 선택

$('#select').val($('#select option').eq(3).val());

jsfiddle 예제

이렇게 하면 됩니다.

<head>
    <script type="text/javascript">
        function Init () {
            var counter = document.getElementById ("counter");
            for (var i = 1; i < 1000; i++) {
                var option = new Option (i, i);
                counter.options.add (option);
            }
            counter.focus ();
        }
        
        function OnKeyPressCounter (event, counter) {
            var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
        
            if (chCode == 68 /* + */) {
                if (counter.selectedIndex < counter.options.length - 1) {
                    counter.selectedIndex++;
                }
            }
            if (chCode == 45 /* - */) {
                if (counter.selectedIndex > 0) {
                    counter.selectedIndex--;
                }
            }
        }
    </script>
</head>
<body onload="Init ()">
    Use the + and - keys to increase/decrease the counter.
    <select id="counter" onkeypress="OnKeyPressCounter(event, this)" style="width:80px"></select>
</body>

언급URL : https://stackoverflow.com/questions/1314245/set-the-selected-index-of-a-dropdown-using-jquery

반응형