maciejka maciejka - 2 months ago 13
Javascript Question

Check number of options of Drop Down List

I use the Drop Down List.

Html.DropDownList("MealsSelectedHousesMeals", Model["SelectedMeals"], new { id= "MealsSelectedHousesMeals" })


I change dynamically size of it using buttons and javascript actions.
In one of script I check weather this list is empty and then I set content of label.

var labelMealType = document.getElementById('labelMealType');
if ($('#MealsSelectedHousesMeals').length >=1)
{
labelMealType.innerHTML = $('#ListBoxSelectedHousesMeals option:selected').text().split(';')[1];
}
else
{
labelMealType.innerHTML = 'Selected Meal';
}


If this list is empty after a few actions in label shows me caption
undefined
instead
'Selected Meal'

Definition of label.

@Html.Label("Selected Meal",new { id= "labelMealType", style = "border: 1px solid black;font: 12px;" })


Do I check in wrong way quantity of options in SelectListItem?

Answer Source

You are not counting the right thing. Instead of:

$('#MealsSelectedHousesMeals').length >=1

Do:

$('#MealsSelectedHousesMeals>option').length >=1