Reputation: 153
I have a jQuery UI selectmenu
which is dynamically populated hence I have no option to set "selected" attribute in one of the options.
for (var i = 0; i < Data.length; i++)
{
$("#ListID").append($("<option></option>").val(Data[i].ColorName).html(Data[i].ColorName));
}
Also, I'v tried various other methods for setting the values as selected such as:
$('#ListID').val(Data[0].ColorName);
didn't work
$("#ListID[value='" + Data[0].ColorName + "']").attr('selected', 'selected');
didn't work
$('#ListID').selectmenu("refresh");
<=this shows the last value but still it isn't selected as on submit it shows blank value
So, How should I pre-select the option in the selectmenu
to the first i.e 0th element of the array
The problem is it always forces the user to select an option from the drop down which else it shows blank value on submit which shouldn't be the case since I am pre-selecting one value.
Upvotes: 0
Views: 1477
Reputation: 717
Let's try on this select.
<select id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
We want to select mercedes in jquery dynamically for example.
$("#cars option[value='mercedes']").prop('selected', true);
option[value=''] is a selector.
Jsfiddle: https://jsfiddle.net/onurgule/t4obc56s/
jQuery UI fiddle: https://jsfiddle.net/onurgule/p44mta9e/
Upvotes: 0
Reputation: 937
Just i have made a simple selection by making an array of colors, please get your idea from here and let me know if it works.
$("#ListID").selectmenu();
var Data = [{ColorName:"orange"},{ColorName:"blue"},{ColorName:"green"},{ColorName:"red"}];
var selected = "blue";
for (var i = 0; i < Data.length; i++)
{
var select = '';
if(selected==Data[i].ColorName){
select = "selected=selected";
}
$("#ListID").append($("<option "+select+"></option>").val(Data[i].ColorName).html(Data[i].ColorName));
}
$("#ListID").selectmenu("refresh");
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<select id="ListID">
</select>
Upvotes: 0
Reputation: 786
try this:
for (var i = 0; i < Data.length; i++)
{
$("#ListID").append("<option value='"+Data[i].ColorName+"' "+(i == 0 ? "selected":"")+">"+Data[i].ColorName+"</option>");
}
or
for (var i = 0; i < Data.length; i++)
{
$("#ListID").append($("<option "+(i == 0 ? "selected":"")+"></option>").val(Data[i].ColorName).html(Data[i].ColorName));
}
Use selected on option you want to be selected.
Upvotes: 1