Archive for category jQuery

When your Boolean parameter says “oncheck” in JavaScript and what to do about it

In my MVC application, I was building a table using a partial view. One column was an HTML link whose onclick event was bound to the “show” method, and this method took two parameters, a string and a boolean:

 <table>
   <tr>
      <td><a onclick="show('@item.ID', '@item.IsVisible')">Click Me!</a></td>
   </td>
 </table>

Inside the “show” method, notice the “visible” checkbox. I am simply setting the “checked” property to true or false, depending on the value of the “visible” parameter:

function show(id, visible) {
 $("#id").val(id);
 $('#visible').prop('checked', visible);
}

When running this code, I got strange behavior, and using the Developer Tools (F12 in IE), I noticed that the string generating the edit button line looked like this:

 <td><a onclick="show('1', 'checked')">Click Me!</a></td>

Huh. How did that “checked” get in there? When I ran the debugger, and MVC code was correctly binding the Boolean variable to either “True” or “False”, so what’s with this “checked” things I’m seeing?

There were two problems here. First, I needed to modify the MVC code, calling the “ToString” method on the Boolean property:

    <td><a onclick="show('@item.ID', '@item.IsVisible.ToString()')">Click Me!</a></td>

Second, this would return “True” or “False”, with the first letter capitalized. JavaScript needs those values in lower case. So I set up a ternary operator to handle that:

function show(id, visible) {
  $('#visible').prop('checked', visible == "True" ? true : false);
}

Fixed!

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

Calling a .NET web service using jQuery

I was attempting to call a .NET web service using jQuery, but was getting this error message:

An attempt was made to call the method \u0027GetCoasters\u0027 using a GET request, which is not allowed

The key to fixing this was to attach the “ScriptMethod” attribute to the web service and setting the “UseHttpGet” property to “true”, which I show below:

[System.Web.Script.Services.ScriptService]
public class OdometerService : System.Web.Services.WebService {

        [System.Web.Script.Services.ScriptMethod(UseHttpGet = true, 
              ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
        [WebMethod]
        public string GetCoasters() {
            return "Hello World";
        }
 }

And here is me calling the web service – try to contain your excitement:

$.ajax({
 type: "GET",
 url: "http://localhost:12345/CoasterService.asmx/GetCoasters",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (msg) {
      alert('Woohoo!');
 }, error: function (e) {
      alert('Bad stuff - ' + e.responseText);
 }
});

Leave a comment

Give focus to a control in a Bootstrap modal popup window

The times that try men’s’ souls is when you have a Bootstrap modal popup window, and you can’t get the control you want to get focus. So if I have a modal popup window like so:

<div id=”resultsModal” 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”>Update Record</h4>
         </div>

         <div class=”modal-body”>
            <div class=”form-inline” style=”margin-left: auto; margin-right: auto; width: 400px”>
               <div class=”form-group”>
                  <label for=”theDate” >Date: </label>
                  <input type=”text” id=”theDate” class=”form-control” /><br>
                  <input type=”button” id=”save” value=”Save” onclick=”saveRecord() class=”form-control saveButton” />
               </div>
            </div>
         </div>

         <div class=”modal-footer”>
            <button type=”button” class=”btn btn-default” data-dismiss=”modal”>Cancel</button>
         </div>
      </div>
   </div>
</div>

To give focus to the date textbox, I use this little snippet:

$(“#myModal”).on(“shown.bs.modal”, function () {
     $(“#theDate”).focus();
})

 

Leave a comment

Use jQuery to remove HTML table rows beyond the first

I had a table that I need to remove all but the first (header) row from. To do that, I just had a bit of jQuery to query all rows greater than (the “gt” operator) the first:

$(“#resultsTable”).find(“tr:gt(0)”).remove();

 

Leave a comment

Disabling the native date picker control in Chrome

Chrome is my favorite browser, but I hate the native date picker that it uses when the code detects a field marked as a date. To disable it, just use a tiny little snippet of jQuery code:

$(‘input[type=”date”]’).attr(‘type’, ‘text’);

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