Reputation: 2525
I currently have a dropdown list that is populated on page load and sometimes the dropdown list doesn't contain anything and is empty. I would like the hide the dropdown list whenever there aren't any items in the list. I thought i could do this via javascript but i am not sure what i could be doing wrong because after adding the javascript it stills appear on the page.
dropdown select:
<select data-bind="options: endReason() ? endReason().SubReasons : [], value: subReasonId, optionsText: 'Text', optionsValue: 'Value', visible: isChecked"
name="subReasons">
</select>
This is my Javascript:
<script type="text/javascript">
function OnClientDropDownOpening(sender, eventArgs)
{ var combo = $find("<%= subReasons %>");
items = combo.get_items();
if(items.get_count()==0)
{
eventArgs.set_cancel(true);
}
}
</script>
Upvotes: 0
Views: 1484
Reputation: 2368
This should do the job in pure JavaScript:
var select = document.getElementById("select");
var options = select.getElementsByTagName("option");
document.write('Select has ' + options.length + ' options');
Upvotes: 0
Reputation: 229
The following requires that you include the jQuery library.
<script type="text/javascript">
$().ready(function () {
if ($('select[name=subReasons]').length == 0)
$('select[name=subReasons]').remove();
});
</script>
Upvotes: 0
Reputation: 1039588
Why javascript? Seems a complete waste of bandwidth when you could use a condition on the server side and not even render the ddl if there aren't any elements to render:
@if (Model.Items.Count() > 0)
{
@Html.DropDownListFor(x => x.SelectedItemId, Model.Items)
}
Upvotes: 6