1

For some reason I'm having trouble selecting an existing blank value in a dropdown with jQuery. The blank option exists, but setting it via $('#studyList option[value=""]').prop('selected', 'selected'); does not work (nor does .prop('selected', true)). Am I doing something wrong?

$('#studyList').append(
          $('<option value="155" selected="selected">Study 1</option>'));
$('#studyList').append(
          $('<option value="157">Study 2</option>'));
        
$('#studyList').prepend("<option value='' ></option>");

function clear() {
   $('#studyList option[value=""]').prop('selected', 'selected');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="studyList"></select>

<button id="clear" onclick="clear();" value="Clear">Clear</button>
Maistrenko Vitalii
  • 994
  • 1
  • 8
  • 16
gene b.
  • 10,512
  • 21
  • 115
  • 227

3 Answers3

1

$('#studyList').append(
  '<option value="155" selected="selected">Study 1</option>'
);
$('#studyList').append(
  '<option value="157">Study 2</option>'
);

$('#studyList').prepend("<option value='' ></option>");

$('#clear').on('click', function () {
  $('#studyList').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="studyList"></select>

<button id="clear" value="Clear">Clear</button>
Taplar
  • 24,788
  • 4
  • 22
  • 35
1

Name your function something other than clear as it conflicts with a built-in function

$('#studyList').append(
          $('<option value="155" selected="selected">Study 1</option>'));
$('#studyList').append(
          $('<option value="157">Study 2</option>'));
        
$('#studyList').prepend("<option value='' ></option>");

function xclear() {
   $('#studyList option[value=""]').prop('selected', 'selected');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="studyList"></select>

<button id="clear" onclick="xclear();" value="Clear">Clear</button>

Also, as others have mentioned, you could also just set the value of the select with $('#studylist').val('')

j08691
  • 204,283
  • 31
  • 260
  • 272
0

Try this

$("#studyList").val("");
SSD
  • 1,373
  • 2
  • 13
  • 20