ove
ove

Reputation: 3202

How to assign empty value to select dropdown?

This works with Google Chrome and IE but not Firefox. For some reaons, Chrome and IE allow blank value to be assigned eventhough it is not part of the dropdown selection.

document.getElementById('dropdownid').value = "";

Note that I have access to jQuery but is not doing what i wanted.

$("#dropdownid").val("");

The above JQuery does not set it to a blank value because blank is not part of the dropdown options. I need to assign "" to the dropdown selectedvalue due to some third party legacy code issues.

Any idea?

Upvotes: 10

Views: 72236

Answers (8)

Muhammad Kamran
Muhammad Kamran

Reputation: 151

$("#dropdownid option[value='']").attr('selected', true)

Upvotes: -1

CodingSolutions
CodingSolutions

Reputation: 81

You can try
$(“#elementId”).val('');
e.g. $(“#CountryDD”).val('');

Upvotes: 2

eon
eon

Reputation: 1938

2018 jQuery 3.2.1 answer

If you're chaining methods on a jquery selector, $('#selectId').slideUp(600)[0].selectedIndex = -1 appears to work (at least in Chrome) but bothers my 'stick to one syntax/framework' preference.

This also works: $('#selectId').slideUp(600).find('option[selected]').attr('selected', false);

It's a bit longer, but choose the flavor you prefer.

Upvotes: 0

aafaq ahmad
aafaq ahmad

Reputation: 1

best way is to use $("#dropdownid").html(''); it makes the value null.

Upvotes: 0

Andy
Andy

Reputation: 8918

Couldn't you add a blank option to the select before setting it?

var jqDropdown = $('#dropdownid');
if (!jqDropdown.find('option[value=""]').length) {
  jqDropdown.prepend($('<option value=""></option>'));
}
jqDropdown.val("");

Upvotes: 1

Moob
Moob

Reputation: 16204

Simply change the selectedIndex. E.G:

$(function(){
    $dropdown = $("#dropdownid");
    alert($dropdown.val()); //alerts "2"
    $dropdown[0].selectedIndex = -1; //or document.getElementById('dropdownid').selectedIndex = -1;
    alert($dropdown.val()) //alerts null
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="dropdownid">
    <option value="1">1</option>
    <option value="2" selected="selected">2</option>
    <option value="3">3</option>
</select>

http://jsfiddle.net/kxoytdg8/

Upvotes: 4

Sumit
Sumit

Reputation: 1669

Have you tried un-selecting the options in the select?

$("#dropdownid option").prop("selected", false);

Upvotes: 0

Tetaxa
Tetaxa

Reputation: 4403

Setting selectedIndex to -1 clears the selection.

document.getElementById('dropdownid').selectedIndex = -1;

Upvotes: 13

Related Questions