Reputation: 5790
A very easy one but i find it very difficult.I have one drop down in which values generated at runtime.
<select id="cmbCitySub" name="cmbCitySub" multiple="multiple">
<asp:Literal ID="litCitySub" runat="server"></asp:Literal>
</select>
I have used jquery multiselect plugin in drop down.
$('#cmbCitySub').multiselect({
noneSelectedText: 'Select CitySub',
selectedList: 1,
multiple: false
}).multiselectfilter();
My above drop down is optional i.e. if user doesnt select any value default 0 should be set . i have tried it in jquery BUT FAILED...!!
if ($('#cmbCitySub').val() == null)
{
$('#cmbCitySub').val('0');
}
var sCitySub = $('#cmbCitySub').val();
alert(sCitySub);
Upvotes: 0
Views: 5020
Reputation: 3229
Since no value has been given for the default value 'Select Citysub', the value field will be empty
So, try a check like this:
if($.trim($('#cmbCitySub').val()) == '')
{
$('#cmbCitySub').val('0');
}
Upvotes: 0
Reputation: 541
Check the value of DropDown in doccument load of your page like this.
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
alert('No of Options Present in the Dropdown :' + $('#cmbCitySub option').length);
if ($('#cmbCitySub option').length == 0) {
$("#cmbCitySub").html("<option value='0'>No Value</option>");
$("#cmbCitySub").val(0);
alert('Current Value:' + $("#cmbCitySub").val());
}
});
</script>
Upvotes: 0
Reputation: 35572
if(document.getElementById('cmbCitySub').selectedIndex == -1)
var sCitySub = 0;
Upvotes: 1
Reputation: 541
Try the following code.
if($('#cmbCitySub option').length == 0)
{
$("#cmbCitySub").html("<option value='0'>No Value</option>");
$("#cmbCitySub").val(0);
alert($("#cmbCitySub").val());
}
Upvotes: 1