0

I want to make number 90 as default value. Anyone know how to apply selected element like in HTML below into jQuery?

Example in HTML

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

How to apply selected in jQuery whereby number 90 as default value?

$("#threshold").append($("<option>",{value: "70",text: "70%"}));
$("#threshold").append($("<option>",{value: "80",text: "80%"}));
$("#threshold").append($("<option>",{value: "90",text: "90%"}));
mastersuse
  • 936
  • 1
  • 15
  • 35

2 Answers2

1

Either

$("#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>

or

$("#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>

shorter:

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

Just tell jQuery which one should be selected by adding selected: true in the object

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>
Andreas
  • 21,535
  • 7
  • 47
  • 56