user3375391 user3375391 - 19 days ago 6
HTML Question

jQuery: select element preselect option fail

In this simple fiddle I tested to select an option from the select element by jQuery, which does work, once... But if I want to clear preselection and set it again, for multiple times (use both buttons a second time), it doesn't change anymore... I tried it in firefox and chrome.

Why this? Haven't found a solution yet:(

HTML:

<select>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
<button id="select2">preselect 2nd</button>
<button id="selectNone">preselect none</button>


Javascript:

$("#select2").click(function() {
$("select option:nth-of-type(2)").attr("selected", true);
});

$("#selectNone").click(function() {
$("option").attr("selected", false);
});


Thanks in advance!
Severin

Answer

Setting the selected attribute doesn't work because the selected attribute isn't the current selected state of an option; it's the default selected state of an option.

Just use val, with the options pseudo-array in the first case:

$("#select2").click(function() {
  var select = $("select");
  select.val(select[0].options[2].value);
});

$("#selectNone").click(function() {
  $("select").val(null);
});

$("#select2").click(function() {
  var select = $("select");
  select.val(select[0].options[2].value);
});

$("#selectNone").click(function() {
  $("select").val(null);
});
<select>
  <option value="1">Test 1</option>
  <option value="2">Test 2</option>
  <option value="3">Test 3</option>
</select>
<button id="select2">preselect 2nd</button>
<button id="selectNone">preselect none</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or alternately, using the selected property on the option:

$("#select2").click(function() {
  $("select option:nth-of-type(2)").prop("selected", true);
});

$("#selectNone").click(function() {
  $("select").val(null);
});

$("#select2").click(function() {
  $("select option:nth-of-type(2)").prop("selected", true);
});

$("#selectNone").click(function() {
  $("select").val(null);
});
<select>
  <option value="1">Test 1</option>
  <option value="2">Test 2</option>
  <option value="3">Test 3</option>
</select>
<button id="select2">preselect 2nd</button>
<button id="selectNone">preselect none</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments