1. ホーム
  2. javascript

[解決済み] jQuery select option elements by value

2023-02-19 19:52:55

質問

select要素をspan要素で囲んでいます。selectのidは使用できませんが、spanのidは使用することができます。 私はjavascript/jquery関数を書こうとしています。入力は数字iで、selectのオプションの値の1つです。この関数は、関連するオプションをselectedにします。

<span id="span_id">
    <select id="h273yrjdfhgsfyiruwyiywer" multiple="multiple">
        <option value="1">cleaning</option>
        <option value="2">food-2</option>
        <option value="3">toilet</option>
        <option value="4">baby</option>
        <option value="6">knick-knacks</option>
        <option value="9">junk-2</option>
        <option value="10">cosmetics</option>
    </select>
</span>

というようなことを書きました(これが完全に動作しないので、この質問を投稿しています)。

function select_option(i) {

    options = $('#span_id').children('select').children('option');
    //alert(options.length); //7
    //alert(options[0]); //[object HTMLOptionElement]
    //alert(options[0].val()); //not a jquery element
    //alert(options[0].value); //1

    //the following does not seem to work since the elements of options are DOM ones not jquery's
    option = options.find("[value='" + i + "']");
    //alert(option.attr("value")); //undefined
    option.attr('selected', 'selected');

}

ありがとうございます。

どのように解決するのですか?

ここでは、明確なセレクタを使用した最も簡単な解決方法を紹介します。

function select_option(i) {
  return $('span#span_id select option[value="' + i + '"]').html();
}