Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run JavaScript block depending on ViewBag value

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;
like image 643
James Avatar asked Aug 09 '26 12:08

James


1 Answers

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>
like image 82
Felix Cen Avatar answered Aug 12 '26 09:08

Felix Cen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!