Archive for category JavaScript

JavaScript countdown timer

I needed a timer to let users know they have fifteen minutes to complete a request. First, the script:

    var end = new Date().getTime() + (15 * 60000);

    var d = setInterval(function () {

        var now = new Date().getTime();
        var distance = end - now;

        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        document.getElementById("timer").innerHTML = "

Please complete the " +             "request within 15 minutes.
Time remaining: " + minutes + ":" + seconds + "

";         if (distance

The “timer” DIV here is without all the awesome styling I have on the one in my application, but I’m sure you can center your own text:

Advertisements

Leave a comment

Converting a JavaScript date to the short format (US)

Messing around with JavaScript / jQuery, the date object I was getting back was the Ajax call was being returned in the format Year-Month-Day (2017-06-02). I wanted it Month-Day-Year (06/02/2017). So I created a JS Date object from the string returned, then call the “toLocaleDateString” method call. In this example, “d” is the variable returned from the Ajax call

...
success: function(d) {
if (d != null) {
     var date = new Date(d.Date);
     $("#Date").val(date.toLocaleDateString());
  }
}

Leave a comment

Bootstrap modal popup window persists

I had a problem with Bootstrap modal popup window not going away properly. I was returning search results in an MVC application, and if there were multiple results returned, the popup would be displayed. The modal popup was standard code you see on the Bootstrap web site, and I had a jQuery method to get results from a Web API call and, after a successful result, would close the popup by programmatically clicking the modalClose button:

function getEmpInfo(id) {
    var url = 'http://localhost:12345/api/EmpController/';

    $.ajax({
        url: url + '?id=' + id,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (d) {
            populateGeneralInfo(d);
            $("#modalClose").click();
        }
    });
}

As I said, if the getEmpInfo once, it would work, but more than once and the page would basically freeze – the entire screen would disabled. The popup window itself would disappear, but the page stayed dark.

After using the IE developer tools, I noticed that there was a modal DIV tag that was remaining, and that was causing the problem:


To resolve this, I modified the success callback of the getEmpInfo JS method, and added code to remove that recalcitrant DIV:

        success: function (d) {
            populateGeneralInfo(d);
            $("#modalClose").click();
            $('div[class*="modal-backdrop"]').remove();
        }

Leave a comment

An “IN” clause for jQuery

I wanted to use jQuery to determine if a code selected by a user (the “code” variable below) was in a static list of codes. So basically, I wanted it to act like a SQL “IN” clause. To do that, I used jQuery’s .inArray operator:

var codeList = ['1', '2', '3', '4'];
if (code.length > 0 && $.inArray(code, codeList) > -1) { ... }

Leave a comment

MVC Checkbox always true

In my MVC view, I had checkbox, like so:

@Html.CheckBoxFor(m => m.IsComplete)

A button click event called a jQuery method to pull the value of the checkbox to send it to a Web API call:

$("#IsComplete").val()

The problem was that the checkbox value in jQuery was always true, whether or not it was checked on the view. To correct this, I had to abandon the “val()” method and instead used the “:checked” operator:

   var isChecked = $("input[name='IsComplete']:checked").length;
   var isComplete = false;

   if (isChecked == 1) {
       isComplete = true;
   }

Leave a comment

Textbox not updating from jQuery AJAX call

I had a friendly little piece of JavaScript code to return a string to the calling code:

function getDescByCode(code) {
    var returnVal;

    $.ajax({
        url: "http://www.scott.bla/api/ReturnMyStringValue",
        type: "GET",
        data: { code: code }
    })
    .done(function (data) {
        returnVal = data;
    });
    
    return returnVal;
}

This method was being called by an onchange event assigned to an MVC drop down list to update a textbox, so when a user changed the value of the DDL, the associated textbox would be changed to the value returned from the Web API call, which was called from the function above:

@Html.DropDownListFor(m => m.MyCode, 
(IEnumerable<SelectListItem>)Application["Codes"], 
"--Select--", 
new { @onchange = "$('#MyDesc').val(getDescByCode(this.value));" })
   @Html.TextBoxFor(m => m.MyDesc)

The problem was that the text box wasn’t being updated. However, if I added an alert inside the jQuery method, I could see that the data was, in fact, being returned from the Web API called as expected:

    .done(function (data) {
       alert(data);    // Worked
    });

The problem was solved by adding the “async: false” line to the AJAX call. The full working method is:

function getDescByCode(code) {
    var returnVal;

    $.ajax({
        url: "http://www.scott.bla/api/MyStuff",
        type: "GET",
        async: false,
        data: { code: code }
    })
    .done(function (data) {
        returnVal = data;
    });
    
    return returnVal;
}

Leave a comment

Hiding zero-value items in Google Charts

Working with Google Charts, I had three values I was putting into a bar chart. There were times when some of the values would be zero, and I didn’t want them to show. Usually, they didn’t, but once in a while, a sliver of red would peak through, as you can see in the image:

Google Charts

Google Charts

To get around this, I explicitly set the value in question to null instead of zero. So in my loop where I bind the data to the chart, I check to see if the value is zero. I’ve included the entire function for continuity. The variable “finalData” is a class passed from a Web API call, and the Foods is a generic List of class Food, which has four properties: Name, Ate, Eating, and WillEat:

function renderChart(finalData) {
var data = new google.visualization.DataTable();

data.addColumn(‘string’, ‘Text’);
data.addColumn(‘number’, ‘Ate’);
data.addColumn({ ‘type’: ‘string’, ‘role’: ‘tooltip’, ‘p’: { ‘html’: true } })
data.addColumn(‘number’, ‘Eating’);
data.addColumn({ ‘type’: ‘string’, ‘role’: ‘tooltip’, ‘p’: { ‘html’: true } })
data.addColumn(‘number’, ‘Will Eat’);
data.addColumn({ ‘type’: ‘string’, ‘role’: ‘tooltip’, ‘p’: { ‘html’: true } })
data.addColumn({ type: ‘string’, role: ‘annotation’ });

data.addRows(finalData.Foods.length);

for (var i = 0; i < finalData.Foods.length; i++) {

if (finalData.Foods[i] != null && finalData.Foods[i].Eating== 0) {
finalData.Foods[i].Eating= null;
}

data.setValue(i, 0, finalData.Foods[i].Name);
data.setValue(i, 1, finalData.Foods[i].Ate);
data.setValue(i, 2, ‘<p style=”font-size: 12; text-align: center; vertical-align: middle”>Ate</p>’);
data.setValue(i, 3, finalData.Foods[i].Eating);
data.setValue(i, 4, ‘<p style=”font-size: 12; text-align: center; vertical-align: middle”>Eating</p>’);
data.setValue(i, 5, finalData.Foods[i].WillEat);
data.setValue(i, 6, ‘<p style=”font-size: 12; text-align: center; vertical-align: middle”>Will Eat</p>’);
data.setValue(i, 7, ”);
}

var options = {
title: ‘Favorite Foods’,
titleTextStyle: { ‘fontSize’: 22 },
fontSize: 12,
width: 570,
height: 275,
legend: { position: ‘none’ },
isStacked: true,
tooltip: { isHtml: true, textStyle: { fontName: ‘Arial’, fontSize: 16 } },
series: {
0: { color: ‘green’ },
1: { color: ‘red’ },
2: { color: ‘blue’ },
}
};

var chart = new google.visualization.BarChart(document.getElementById(‘chartDiv’));
chart.draw(data, options);
}

Leave a comment