Archive for category JavaScript

jQuery autocomplete appears behind Bootstrap modal window

I sure do love those Bootstrap modal popup windows. I use them all the time. They make me feel cool when I use them, and increase my self-esteem greatly. It’s like getting a participation medal when you’re the last place team in soccer, or a more fun sport.

Almost as much as modal popups, I love jQuery autocomplete lists, where you can enter a bit of text and have results returned from the database. Wow, those are fun to play around with. And users love them, too.

Alas, when I tried to bring my two favorite coding snippets together like a Reese’s peanut butter cup, things didn’t turn out well. Here is what the results looked like:

Completely unacceptable – half my list is hidden, and the rest are basically greyed-out. There was much sorrow and gnashing of teeth.

The key to fixing it was the “ui-front” class of the jQuery-ui.css file. Who knew such a small class could bring such happiness? To use the class in this instance, I needed to attach it to the DIV tag containing my textbox, like so:

<div id=”addEmployeeModal” class=”modal fade” role=”dialog”>
   <div class=”modal-dialog”>
      <div class=”modal-content”>
         <div class=”modal-header”>
            <button id=”modalClose” type=”button” class=”close” data-dismiss=”modal”>&times;</button>
<h4 class=”modal-title text-center”>Add employee</h4>
</div>
<div class=”modal-body ui-front“>
@Html.TextBox(“Employee”, null, new { @class = “form-control” })
<input type=”button” value=”Save” onclick=”functionToCallAutocomplete()  />
<
/div>
</div>
</div>
</div>

Now you, too, can enjoy the peanut butter and chocolate joy of using a Bootstrap modal popup and jQuery autocomplete controls.

Advertisements

Leave a comment

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:

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