I applied a replacement for a dropdown-menu and the jQuery replacement stays empty because the preselected value of the select-option-form is undefined (the values are generated dynamically). When I click the replacement and choose an option it works as it should. Here is the excerpt of the replacement code I think it is responsible for the error:
function createDropDownSF(){
var searchForm_type = $("#searchForm_type");
var selected = searchForm_type.find("option[selected]");
var options = $("option", searchForm_type);
Therefore I tried to extend the function with this code, to make the function use the first option available when there is no selected value, but it doesn't work:
if (selected.is("undefined")) {
searchForm_type.find("option")[0];
}
Does anyone has an idea?
I would first try to get a list off al the options that are selected and check if the length > 0.
$("select option:selected").length > 0
Then you can use JQuery to select the first option.
$('select option').first().attr('selected', true);
Did you mean it that way?
function createDropDownSF(){
var searchForm_type = $("#searchForm_type");
var selected = searchForm_type.find("option[selected]");
$("select option:selected").length > 0;
$('select option').first().attr('selected', true);
var options = $("option", searchForm_type);
<select id="test">
<option>1</option>
<option>2</option>
<option selected="selected">3</option>
<option>4</option>
$(function () {
if ($("#test option:selected").length > 0) {
// something is selected
alert("selected");
} else {
// nothing is selected
$('#test option').first().attr('selected', true);
}
});
I don't know how to set the select that is doesn't have a value selected, but this code should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.