Как применить «выбранный» элемент в jQuery? - PullRequest
0 голосов
/ 08 ноября 2019

Я хочу сделать число 90 в качестве значения по умолчанию. Кто-нибудь знает, как применить элемент selected, как в HTML ниже, в jQuery?

Пример в HTML

<select id="threshold">
    <option value="90" selected>90</option>   /* example selected in HTML */
</select>

Как применить selected в jQuery, с помощью которого число90 в качестве значения по умолчанию?

$("#threshold").append($("<option>",{value: "70",text: "70%"}));
$("#threshold").append($("<option>",{value: "80",text: "80%"}));
$("#threshold").append($("<option>",{value: "90",text: "90%"}));

Ответы [ 2 ]

1 голос
/ 08 ноября 2019

Либо

$("#threshold").append($("<option>",{ value: "90",text: "90%", selected:true }));

$("#threshold")
.append($("<option>",{value: "70",text: "70%"}))
.append($("<option>",{value: "80",text: "80%"}))
.append($("<option>",{value: "90",text: "90%", selected:true }))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="threshold">
</select>

или

$("#threshold")
  .append($("<option>",{value: "90",text: "90%"}))
  .val("90");

$("#threshold")
.append($("<option>",{value: "70",text: "70%"}))
.append($("<option>",{value: "80",text: "80%"}))
.append($("<option>",{value: "90",text: "90%"}))
.val(90);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="threshold">
</select>

короче:

const curTH = 90;
$.each([70, 80, 90], (_, item) =>
  $("<option>",{ value: item, text: item + "%", "selected": item === curTH ? true : false })
  .appendTo("#threshold")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="threshold">
</select>
0 голосов
/ 08 ноября 2019

Просто скажите jQuery, какой из них следует выбрать, добавив selected: true в объект

const options = [
   {value: "70",text: "70%"}
  ,{value: "80",text: "80%"}
  ,{value: "90",text: "90%", selected: true}
];

$("#threshold").append(options.map(o => $("<option>", o)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="threshold"></select>
...