IT

jQuery 세트 선택 색인

lottoking 2020. 4. 2. 08:23
반응형

jQuery 세트 선택 색인


선택 상자가 있습니다.

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
  <option value="3">Number 3</option>
  <option value="4">Number 4</option>
  <option value="5">Number 5</option>
  <option value="6">Number 6</option>
  <option value="7">Number 7</option>
</select>

선택한 색인을 기반으로 옵션 중 하나를 "선택됨"으로 설정하고 싶습니다.

예를 들어 "번호 3"을 설정하려고하면 다음과 같이 시도합니다.

$('#selectBox')[3].attr('selected', 'selected');

그러나 이것은 작동하지 않습니다. jQuery를 사용하여 색인을 기반으로 선택한 옵션을 어떻게 설정할 수 있습니까?

감사!


참고 : 답변은 jQuery 1.6.1+에 따라 다릅니다.

$('#selectBox :nth-child(4)').prop('selected', true); // To select via index
$('#selectBox option:eq(3)').prop('selected', true);  // To select via value

주석에 감사드립니다 .get.jQuery 요소가 아닌 DOM 요소를 반환하므로 작동하지 않습니다. 명심 .eq기능뿐만 아니라 원하는 경우 선택기의 사용 외부 될 수 있습니다.

$('#selectBox option').eq(3).prop('selected', true);

특정 인덱스 를 선택하는 대신 을 사용하려는 경우 더 간결하고 읽기 쉽습니다 .

$("#selectBox").val("3");

참고 : .val(3) 이 예제에서도 잘 작동하지만 숫자가 아닌 값은 문자열이어야하므로 일관성을 위해 문자열을 선택했습니다.
(예 <option value="hello">Number3</option>:)를 사용해야 .val("hello")합니다.


이것은 또한 유용 할 수 있으므로 여기에 추가 할 것이라고 생각했습니다.

해당 항목의 색인이 아닌 항목의 값을 기준으로 값을 선택하려면 다음을 수행하십시오.

선택 목록 :

<select id="selectBox">
    <option value="A">Number 0</option>
    <option value="B">Number 1</option>
    <option value="C">Number 2</option>
    <option value="D">Number 3</option>
    <option value="E">Number 4</option>
    <option value="F">Number 5</option>
    <option value="G">Number 6</option>
    <option value="H">Number 7</option>
</select>

jquery :

$('#selectBox option[value=C]').attr('selected', 'selected');

$('#selectBox option[value=C]').prop('selected', true);

선택한 항목은 이제 "번호 2"입니다.


대신 이것을 시도하십시오 :

$("#selectBox").val(3);

또한 이것이 도움이되는지 확인하십시오.

http://elegantcode.com/2009/07/01/jquery-playing-with-select-dropdownlistcombobox/


더 간단합니다 :

$('#selectBox option')[3].selected = true;

# Set element with index
$("#select option:eq(2)").attr("selected", "selected");

# Set element by text
$("#select").val("option Text").attr("selected", "selected");

세트 선택을위한 최상의 방법으로 선택하려면
$('#select option').removeAttr('selected');이전 선택을 제거 하는 데 사용할 수 있습니다 .

# Set element by value
$("#select").val("2");

# Get selected text
$("#select").children("option:selected").text();  # use attr() for get attributes
$("#select option:selected").text(); # use attr() for get attributes 

# Get selected value
$("#select option:selected").val();
$("#select").children("option:selected").val();
$("#select option:selected").prevAll().size();
$("option:selected",this).val();

# Get selected index
$("#select option:selected").index();
$("#select option").index($("#select option:selected"));

# Select First Option
$("#select option:first");

# Select Last Item
$("#select option:last").remove();


# Replace item with new one
$("#select option:eq(1)").replaceWith("<option value='2'>new option</option>");

# Remove an item
$("#select option:eq(0)").remove();

무엇 이해하는 것이 중요하기 때문이다 val()A에 대한 select처럼 요소 요소의 수를 선택한 옵션의 값을 반환하지만 selectedIndex자바 스크립트.

옵션을 선택하려면 value="7"다음을 사용하십시오.

$('#selectBox').val(7); //this will select the option with value 7.

옵션을 선택 해제하려면 빈 배열을 사용하십시오.

$('#selectBox').val([]); //this is the best way to deselect the options

물론 여러 옵션을 선택할 수 있습니다 * :

$('#selectBox').val([1,4,7]); //will select options with values 1,4 and 7

* 여러 옵션을 선택 하더라도 <select>요소에는 MULTIPLE속성이 있어야합니다 . 그렇지 않으면 작동하지 않습니다.


나는 항상 prop ( 'selected')에 문제가 있었으며 다음은 항상 나를 위해 일했습니다.

//first remove the current value
$("#selectBox").children().removeAttr("selected");
$("#selectBox").children().eq(index).attr('selected', 'selected');

이 시도:

$('select#mySelect').prop('selectedIndex', optionIndex);

결국 .change 이벤트를 트리거하십시오.

$('select#mySelect').prop('selectedIndex', optionIndex).change();

이것이 너무 도움이되기를 바랍니다.

$('#selectBox option[value="3"]').attr('selected', true);

세 번째 옵션을 선택하십시오

$('#selectBox').val($('#selectBox option').eq(2).val());

jsfiddle의 예


NB :

$('#selectBox option')[3].attr('selected', 'selected') 

배열 지연은 jquery 객체가 아닌 dom 객체를 가져 오므로 예를 들어 "$ ( '# selectBox option') [3] .attr () 함수가 아닌 FF에서 TypeError와 함께 실패합니다. "


Marc와 John Kugelman의 대답을 명확히하기 위해 다음을 사용할 수 있습니다.

$('#selectBox option').eq(3).attr('selected', 'selected')

get() jQuery 객체가 아닌 DOM 객체를 가져 오기 때문에 지정된 방식으로 사용하면 작동하지 않으므로 다음 솔루션이 작동하지 않습니다.

$('#selectBox option').get(3).attr('selected', 'selected')

eq()지정된 인덱스를 가진 jQuery를 요소의 필터로 설정하는 필터를 가져옵니다. 보다 명확합니다 $($('#selectBox option').get(3)). 그다지 효율적이지 않습니다. $($('#selectBox option')[3])더 효율적입니다 ( 테스트 사례 참조 ).

실제로 jQuery 객체는 필요하지 않습니다. 이것은 트릭을 할 것입니다 :

$('#selectBox option')[3].selected = true;

http://api.jquery.com/get/

http://api.jquery.com/eq/

또 다른 중요한 점 :

"selected"속성은 선택한 라디오 버튼을 지정하는 방법이 아닙니다 (최소한 Firefox 및 Chrome에서). "checked"속성을 사용하십시오 :

$('#selectBox option')[3].checked = true;

확인란도 마찬가지입니다.


1.4.4에서 $ ( "# selectBox option") [3] .attr 함수가 아닙니다

이것은 작동합니다 : $('#name option:eq(idx)').attr('selected', true);

여기서 #nameselect id는 선택 idx하려는 옵션 값입니다.


순수한 자바 스크립트 selectedIndex 속성은 올바른 자바 스크립트 이므로 브라우저 간 작동하기 때문에 올바른 방법입니다.

$('#selectBox')[0].selectedIndex=4;

다음은 하나를 사용하여 다른 하나를 사용하여 두 개의 드롭 다운 이있는 jsfiddle 데모 입니다.

<select onchange="$('#selectBox')[0].selectedIndex=this.selectedIndex">
  <option>0</option>
  <option>1</option>
  <option>2</option>
</select>

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
</select>

옵션 태그에서 "selected"속성이 필요한 경우 selectedIndex를 변경하기 전에 이것을 호출 할 수도 있습니다 ( 여기에는 바이올린 ).

$('#selectBox option').removeAttr('selected')
   .eq(this.selectedIndex).attr('selected','selected');

//funcion para seleccionar por el text del select
var text = '';
var canal = ($("#name_canal").val()).split(' ');
$('#id_empresa option').each(function(i, option) {
        text = $('#id_empresa option:eq('+i+')').text();
        if(text.toLowerCase() == canal[0].toLowerCase()){
            $('#id_empresa option:eq('+i+')').attr('selected', true);
        }
    });

$('#selectBox option').get(3).attr('selected', 'selected')

위의 내용을 사용할 때 웹킷 (Chrome)에 오류가 계속 발생했습니다.

"Uncaught TypeError : Object #에 'attr'메서드가 없습니다."

이 구문은 이러한 오류를 중지합니다.

$($('#selectBox  option').get(3)).attr('selected', 'selected');

선택 목록의 값을 기준으로 항목을 선택하십시오 (특히 옵션 값에 공백이나 이상한 문자가있는 경우).

$("#SelectList option").each(function () {
    if ($(this).val() == "1:00 PM")
        $(this).attr('selected', 'selected');
});

또한 (다중 선택과 달리) 드롭 다운이 있으면 break;첫 번째 값을 덮어 쓰지 않도록 할 수 있습니다.


js 파일에 하드 코딩 된 값이없는 솔루션이 필요합니다. 사용하여 selectedIndex. 주어진 솔루션의 대부분이 하나의 브라우저에서 실패했습니다. 이것은 FF10 및 IE8에서 작동하는 것으로 보입니다 (다른 버전에서 다른 사람이 테스트 할 수 있음)

$("#selectBox").get(0).selectedIndex = 1; 

항목의 특정 속성을 기반으로 항목을 선택하려면 [prop = val] 유형의 jQuery 옵션이 해당 항목을 가져옵니다. 이제는 항목별로 값을 원했던 색인에 신경 쓰지 않습니다.

$('#mySelect options[value=3]).attr('selected', 'selected');

나는 같은 문제에 직면했다. 먼저 이벤트를 진행해야합니다 (즉, 어떤 이벤트가 먼저 발생하는지).

예를 들면 다음과 같습니다.

번째 이벤트 는 옵션이있는 선택 상자를 생성 중입니다.

번째 이벤트 는 val () 등과 같은 함수를 사용하여 기본 옵션을 선택합니다.

번째 이벤트 다음에 두 번째 이벤트 가 발생해야합니다 .

이를 위해 두 가지 기능을 사용할 수 있습니다. generateSelectbox () (선택 상자 생성 용) 및 selectDefaultOption ()

당신은 있는지 확인해야합니다 selectDefaultOption는 () 만 실행 한 후 호출되어야합니다 ) (generateSelectbox


선택 상자가 여러 개인 경우 여러 값을 초기화 할 수도 있습니다.

$('#selectBox').val(['A', 'B', 'C']);

나는 종종 트리거 ( '변경')를 사용하여 작동시킵니다.

$('#selectBox option:eq(position_index)').prop('selected', true).trigger('change');

id select = selectA1 및 position_index = 0 인 예 (select의 frist 옵션) :

$('#selectA1 option:eq(0)').prop('selected', true).trigger('change');

selectoption 변수 값을 동적으로 설정하고 옵션을 선택할 수 있습니다. 다음 코드를 시도해 볼 수 있습니다

암호:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

      $(function(){
            $('#allcheck').click(function(){
             // $('#select_option').val([1,2,5]);also can use multi selectbox
              // $('#select_option').val(1);
               var selectoption=3;
           $("#selectBox>option[value="+selectoption+"]").attr('selected', 'selected');
    });

});

HTML 코드 :

   <select id="selectBox">
       <option value="0">Number 0</option>
       <option value="1">Number 1</option>
       <option value="2">Number 2</option>
       <option value="3">Number 3</option>
       <option value="4">Number 4</option>
       <option value="5">Number 5</option>
       <option value="6">Number 6</option>
       <option value="7">Number 7</option>
 </select> <br>
<strong>Select&nbsp;&nbsp; <a style="cursor:pointer;" id="allcheck">click for select option</a></strong>


곧:

$("#selectBox").attr("selectedIndex",index)

여기서 index는 선택된 인덱스 (정수)입니다.

참고 URL : https://stackoverflow.com/questions/1280499/jquery-set-select-index

반응형