IT story

jQuery select2 선택 태그의 값을 얻습니까?

hot-time 2020. 9. 8. 22:00
반응형

jQuery select2 선택 태그의 값을 얻습니까?


안녕 친구 이것은 내 코드입니다.

<select id='first'>
  <option value='1'> First  </option>
  <option value='2'> Second </option>
  <option value='3'> Three  </option>
</select>

이것은 내 select2 코드입니다.

$("#first").select2();

아래는 선택된 값을 얻기위한 코드입니다.

$("#first").select2('val'); // It returns first,second,three.

이것은 같은 텍스트를 반환 first,second,three하고 나는 얻고 싶습니다 1,2,3.
텍스트가 아닌 선택 상자의 값이 필요함을 의미합니다.


$("#first").val(); // this will give you value of selected element. i.e. 1,2,3.

Select 요소를 얻으려면 사용할 수 있습니다. $('#first').val();

선택한 값의 텍스트를 얻으려면- $('#first :selected').text();

select2()기능 코드 를 게시 해 주시겠습니까?


$("#first").select2('data') 모든 데이터를지도로 반환합니다.


이 솔루션을 사용하면 선택 요소를 잊을 수 있습니다. 선택한 요소에 ID가 없을 때 유용합니다.

$("#first").select2()
.on("select2:select", function (e) {
    var selected_element = $(e.currentTarget);
    var select_val = selected_element.val();
});

ajax를 사용하는 경우 선택 직후 select 업데이트 할 수 있습니다 .

//Part 1

$(".element").select2(/*Your code*/)    

//Part 2 - continued 

$(".element").on("select2:select", function (e) { 
  var select_val = $(e.currentTarget).val();
  console.log(select_val)
});

크레딧 : Steven-Johnston


간단한 대답은 다음과 같습니다.

$('#first').select2().val()

이 방법으로도 작성할 수 있습니다.

 $('#first').val()

See this fiddle.
Basically, you want to get the values of your option-tags, but you always try to get the value of your select-node with $("#first").val().

So we have to select the option-tags and we will utilize jQuerys selectors:

$("#first option").each(function() {
    console.log($(this).val());
});

$("#first option") selects every option which is a child of the element with the id first.


Try this :

$('#input_id :selected').val(); //for getting value from selected option
$('#input_id :selected').text(); //for getting text from selected option

Other answers wasn't working for me so i developed solution:

I created option with class="option-item" for easy targeting

HTML :

<select id="select-test">
<option value="5-val" id="first-id" class="option-item"> First option </option>
</select>

Then for every selected option i added display none property

CSS:

option:checked {
   display: none;
}

Now we can add change to our SelectBox to find our selected option with display none property by simple :hidden attribute

JQuery:

$('#select-test').change(function(){
//value 
    $('#select-test').find('.option-item:hidden').val();
//id
    $('#select-test').find('.option-item:hidden').attr('id');
//text
    $('#select-test').find('.option-item:hidden').text();
});

Working fiddle: https://jsfiddle.net/Friiz/2dk4003j/10/


Solution :

var my_veriable = $('#your_select2_id').select2().val();
var my_last_veriable = my_veriable.toString();

참고URL : https://stackoverflow.com/questions/19908273/jquery-select2-get-value-of-select-tag

반응형