programing

jQuery를 사용하여 선택한 옵션 ID 가져오기

telecom 2023. 8. 13. 09:33
반응형

jQuery를 사용하여 선택한 옵션 ID 가져오기

선택한 옵션을 기준으로 jQuery를 사용하여 Ajax 요청을 하려고 합니다.

jQuery를 사용하여 선택한 옵션 ID(예: "id2")를 검색하는 간단한 방법이 있습니까?

<select id="my_select">
   <option value="o1" id="id1">Option1</option>
   <option value="o2" id="id2">Option2</option>
</select>


$("#my_select").change(function() {
    //do something with the id of the selected option
});

다음과 같이 실렉터를 사용하여 얻을 수 있습니다.

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});

var id = $(this).find('option:selected').attr('id');

그러면 당신은 당신이 원하는 것을 무엇이든 합니다.selectedIndex

선택된 이후로 답변을 다시 편집했습니다.예를 들어 인덱스는 좋은 변수가 아닙니다.

$('#my_select option:selected').attr('id');

가장 쉬운 방법은 변경 시와 같은 이벤트 내부에서 변수 = $(this).val()입니다.

언급URL : https://stackoverflow.com/questions/2888446/get-the-selected-option-id-with-jquery

반응형