Reputation: 12044
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>
Upvotes: 1
Views: 36
Reputation: 208002
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('')
Upvotes: 1
Reputation: 24965
$('#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>
Upvotes: 1