Nice programing

jQuery를 사용하여 선택 목록에서 선택한 속성 설정

nicepro 2021. 1. 9. 11:40
반응형

jQuery를 사용하여 선택 목록에서 선택한 속성 설정


다음 HTML이 있습니다.

<select id="dropdown">
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>

문자열 "B"가 있으므로 selected속성 을 설정하고 싶습니다 .

<select id="dropdown">
    <option>A</option>
    <option selected="selected">B</option>
    <option>C</option>
</select>

jQuery에서 어떻게할까요?


value옵션 속성 을 포함하기 위해 HTML을 약간 수정해도 괜찮다면이 작업 을 수행하는 데 필요한 코드를 크게 줄일 수 있습니다.

<option>B</option>

...에

<option value="B">B</option>

다음과 같은 작업을하려는 경우 유용합니다.

<option value="IL">Illinois</option>

이를 통해 다음 jQuery가 변경됩니다.

$("select option[value='B']").attr("selected","selected");

속성 사용을 포함 하지 않기로 결정한 경우 value각 옵션을 순환하고 해당 값을 수동으로 확인해야합니다.

$("select option").each(function(){
  if ($(this).text() == "B")
    $(this).attr("selected","selected");
});

<select id="cars">
<option value='volvo'>volvo</option>
<option value='bmw'>bmw</option>
<option value='fiat'>fiat</option>
</select>

var make = "fiat";

$("#cars option[value='" + make + "']").attr("selected","selected");

JQuery를 사용하는 경우 1.6부터 .prop () 메서드를 사용해야합니다.

$('select option:nth(1)').prop("selected","selected");

I'd iterate through the options, comparing the text to what I want to be selected, then set the selected attribute on that option. Once you find the correct one, terminate the iteration (unless you have a multiselect).

 $('#dropdown').find('option').each( function() {
      var $this = $(this);
      if ($this.text() == 'B') {
         $this.attr('selected','selected');
         return false;
      }
 });

You can follow the .selectedIndex strategy of danielrmt, but determine the index based on the text within the option tags like this:

$('#dropdown')[0].selectedIndex = $('#dropdown option').toArray().map(jQuery.text).indexOf('B');

This works on the original HTML without using value attributes.


This can be a solution

$(document).on('change', 'select', function () {
            var value = $(this).val();
            $(this).find('option[value="' + value + '"]').attr("selected", "selected");
        })

You can use pure DOM. See http://www.w3schools.com/htmldom/prop_select_selectedindex.asp

document.getElementById('dropdown').selectedIndex = 1;

but jQuery can help:

$('#dropdown').selectedIndex = 1;

Code:

var select = function(dropdown, selectedValue) {
    var options = $(dropdown).find("option");
    var matches = $.grep(options,
        function(n) { return $(n).text() == selectedValue; });
    $(matches).attr("selected", "selected");
};

Example:

select("#dropdown", "B");

$('#select_id option:eq(0)').prop('selected', 'selected');

its good


Something along the lines of...

$('select option:nth(1)').attr("selected","selected"); 

ReferenceURL : https://stackoverflow.com/questions/1311287/setting-the-selected-attribute-on-a-select-list-using-jquery

반응형