I am trying to run a piece of JavaScript code, but only if a ViewBag value is equal to null. Below is a example:
<script type="text/javascript">
var defDate = @ViewBag.EndDate;
if (defDate == null)
{
$('#dt2').datetimepicker({
locale: 'en-GB',
format: 'L',
showClear: true
});
}
else
{
$('#dt2').datetimepicker({
defaultDate: defDate,
locale: 'en-GB',
format: 'L',
showClear: true
});
}
</script>
However, this doesn't appear to be working, so any help will be greatly appreciated.
EDIT:
I think I have both of these JavaScript blocks to run on start? Should I be making a separate one which runs on start and then runs the relevant (non-starting) function - if that makes sense?
Here is where the ViewBag is initialised as requested:
ViewBag.EndDate = endDateFilter;
You need to wrap the viewbag value in quotes. Try the following
<script type="text/javascript">
var defDate = '@ViewBag.EndDate';
if (defDate == '')
{
$('#dt2').datetimepicker({
locale: 'en-GB',
format: 'L',
showClear: true
});
}
else
{
$('#dt2').datetimepicker({
defaultDate: defDate,
locale: 'en-GB',
format: 'L',
showClear: true
});
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With