Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 760
ove Avatar asked Sep 25 '14 14:09

ove


People also ask

How do I set an empty dropdown value?

Select the dropdown field associated with the dropdown list you wish to edit or create a new dropdown field. Note: For this example, we will select the Priority field. Select the dropdown list where you would like to add the blank value. Click the Edit button or create a new dropdown list by clicking the Add button.

How do you add a value to a drop down list in dynamic?

To add a dropdown list dynamically, you would need to create the HTML <select> element, its label and optionally a <br> tag. In pure JavaScript, you can use the document. createElement() method to programmatically create a dropdown list. Then you can call the Node's appendChild() method or jQuery's .

How do I select a dropdown by value?

A dropdown is represented by <select> tag and the options are represented by <option> tag. To select an option with its value we have to use the selectByValue method and pass the value attribute of the option that we want to select as a parameter to that method.

What does it mean when the value of the selected menu option is an empty?

The logic would be: only display an empty option if the user did not select any other yet. So after the user selected an option, the empty option disappears. Save this answer.


2 Answers

Setting selectedIndex to -1 clears the selection.

document.getElementById('dropdownid').selectedIndex = -1;
like image 73
Tetaxa Avatar answered Oct 04 '22 20:10

Tetaxa


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/

like image 29
Moob Avatar answered Oct 04 '22 19:10

Moob