Archive for category jQuery

jQuery DatePicker – Removing time from a DatePicker control

I had an MVC view with a TextBox control binding to a model property

@Html.TextBoxFor(model => model.Date, String.Empty, new { @class = "form-control" })

This control was bound to a jQuery DatePicker control:

    $(document).ready(function () {
        $("#Date").datepicker({
            minDate: 0
        });
    });

My problem was that when the model was bound from the database, the DatePicker would also show the time, not just the date like I wanted:

 

 

 

 

 

 

 

 

The fix for this is to make the second parameter a format string with only the date:

@Html.TextBoxFor(model => model.IssueDate, "{0:d}", new { @class = "form-control" })
Advertisements

Leave a comment

Slow multiple jQuery autocomplete fields

I’m a fan of the jQuery autocomplete control. I had a page that worked great with one autocomplete control, but after I added a second, that second control was horribly slow (the first was unchanged). Both controls were defined similar to the one here:

$("#Coaster").autocomplete({
    source: function (request, response) {
        if (request.term.length < 4) {
            return;
        }
        var coaster = new Array();
        $.ajax({
            async: false,
            cache: false,
            type: "POST",
            url: uri + "MyControll/Autocomplete",
            data: { "term": request.term },
            success: function (data) {
                for (var i = 0; i < data.length ; i++) {
                    customer[i] = data[i];
                }
            }
        });
        response(coaster);
    },
    select: function (event, ui) {
        $("#CoasterID").val(ui.item.Id);
    }
});

In order to get the second control to respond within a reasonable period of time, I added this code to the end of the Ajax method, which resolved the problem:

$("#Coaster").autocomplete({

        $.ajax({
 …
        })._renderItem = function (ul, item) {
            return $("<li></li>")
                .data("item.autocomplete", item)
        };
});

Leave a comment

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