JQuery: selecting an item preselection option

In this simple violin, I tested to select a parameter from a select jQuery element that works once ... But if I want to clear the preliminary selection and set it again several times (use both buttons a second time), it does not change anymore. .. I tried it in firefox and chrome.

Why is this? Until they found a solution :(

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

+4
source share
2 answers

Attribute setting selected does not work because the attribute is selectednot the current selected state of the parameter; this is the default state of the parameter.

val, - options :

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

, selected :

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

.

var select = $("select");
// for instance set an ID for more than one selectboxes
var option = select.find("option");

$("#select2").click(function() {
  option.eq(1).attr("selected",true);
  select.val(option.eq(1).val()).change();
});

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

https://jsfiddle.net/63wm1r01/23/

select.change();. .

, .

0

Source: https://habr.com/ru/post/1660793/


All Articles