yuhell
yuhell

Reputation: 15

jQuery selected an option after sort

Hello guys I have a problem to select an option.

I have this, I sort, It's ok, but the problem is the selected item is the last option and I would like to select the selected item but how ? I can't select with option value because I generate dynamically option item :

$('#MySelect').html($('#MySelect option').sort(function (a, b) { return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;}));

// I tried this ?
$('#MySelect option:selected').prop('selected', true);
<select id="MySelect">
  <option value="D">D</option>
  <option value="B">B</option>
  <option value="A" selected>A</option>
  <option value="C">C</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I would like to select the selected item without value but only thanks to "selected"
Thanks for your help

Upvotes: 0

Views: 204

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115242

Before sorting get the selected option reference and later select it using prop() method.

// get the selected option and cache it for later use
var $opt = $('#MySelect option:selected');

// sort the options
$('#MySelect').html($('#MySelect option').sort(function(a, b) {
  return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
  // or use
  // return a.text.localeCompare(b.text);
}));

// set the selected property to the calched option
$opt.prop('selected', true);
<select id="MySelect">
  <option value="D">D</option>
  <option value="B">B</option>
  <option value="A" selected>A</option>
  <option value="C">C</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Get the selected value before you use .sort(), then use $('#MySelect').val(t); to set the select again. ( t = selected value)

var t = $('#MySelect option:selected').val();

$('#MySelect').html($('#MySelect option').sort(function(a, b) {
  return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
}))

$('#MySelect').val(t);

Example below

var t = $('#MySelect option:selected').val();

$('#MySelect').html($('#MySelect option').sort(function(a, b) {
  return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
}))

$('#MySelect').val(t);
<select id="MySelect">
  <option value="D">D</option>
  <option value="B">B</option>
  <option value="A" selected>A</option>
  <option value="C">C</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions