A guide on incorporating the input type 'date' for date columns in jqGrid

When using jqGrid for inline editing, a date column is defined in the colmodel with accompanying JavaScript code. However, it can be cumbersome to maintain and produces an unattractive result.

In instances where the browser supports it, how can one utilize the html5 native input type='date' for inline date editing instead of the existing code?

Below is the current colmodel:

{"template":DateTemplate
,"label":"Invoice date",
"name":"Invoicedate",
"index":"Invoicedate",
"editoptions":{
  "dataInit":initDateWithButton
  ,"size":10
  },

"searchoptions":{"dataInit":initDateWithButton
,"size":10,"attr":{"size":10}},"width":50
}

And the corresponding JavaScript:

var DateTemplate = {
    sorttype: 'date', formatter: 'date',
    formatoptions: {
        srcformat: "Y-m-d"
    },

    editoptions: { maxlength: 10, size: 10, dataInit: initDateWithButton },
    editable: true,
    searchoptions: {
        sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
        dataInit: initDateWithButton,
        size: 11,          // for the advanced searching dialog 
        attr: { size: 11 }   // for the searching toolbar 
    }
};

var initDateWithButton = function (elem) {
    ... [omitted for brevity] ...
};

This pertains to an ASP.NET MVC4 application.

Update

Despite attempting the solution provided, there were still issues encountered.

  1. The date template lacks newformat definition, leading to unresolved parsing issues. The suggested replacement line is:

    $(elem).val($.jgrid.parseDate($.jgrid.formatter.date.newformat, orgValue, "Y-m-d"));
    

Subsequently, to address invalid date conversion to long format, the line was updated to $this.val($this.val());

  1. Upon completion of inline date editing, the ISO format remains displayed until the grid is refreshed, causing localized dates to not visually appear immediately.

** Update **

Issues regarding button visibility within columns widths vary across browsers like IE showing buttons while Chrome displays empty spaces. How can this inconsistency be resolved for uniform button visibility?

Answer №1

Your inquiry has piqued my interest, prompting me to develop a demo that functions smoothly in Google Chrome without relying on jQuery UI Datepicker. This demo showcases the output during date editing.

The demo features a column labeled invdate, with the following specifications:

{ name: "invdate", width: 120, align: "center", sorttype: "date",
    formatter: "date", formatoptions: { newformat: "m/d/Y"}, editable: true,
    editoptions: { dataInit: initDateEdit } }

The function initDateEdit is outlined as follows:

var initDateEdit = function (elem, options) {
    // retrieve original value before changing type
    var orgValue = $(elem).val(),
        cm = $(this).jqGrid("getColProp", options.name);

    $(elem).attr("type", "date");
    if ((Modernizr && !Modernizr.inputtypes.date) || $(elem).prop("type") !== "date") {
        // call jQuery UI datepicker if type="date" is not supported
        $(elem).datepicker({
            dateFormat: "mm/dd/yy",
            autoSize: true,
            changeYear: true,
            changeMonth: true,
            showButtonPanel: true,
            showWeek: true
        });
    } else {
        // convert date to ISO
        $(elem).val($.jgrid.parseDate.call(this, cm.formatoptions.newformat, orgValue, "Y-m-d"));
    }
};

I am unfamiliar with <input type="date"/>. It utilizes an input format of date as ISO. To ensure accurate display during editing, I converted the initial text to ISO within the provided code. Similarly, one must also convert edited results back to the formatoptions.newformat. For this scenario, I employed the beforeSaveRow callback method:

onSelectRow: function (rowid) {
    var $self = $(this),
        savedRow = $self.jqGrid("getGridParam", "savedRow");
    if (savedRow.length > 0 && savedRow[0].id !== rowid) {
        $self.jqGrid("restoreRow", savedRow[0].id);
    }
    $self.jqGrid("editRow", rowid, {
        keys: true,
        beforeSaveRow: myBeforeSaveRow
    });
}

The function myBeforeSaveRow is described as follows:

var myBeforeSaveRow = function (options, rowid) {
    var $self = $(this), $dates = $("#" + $.jgrid.jqID(rowid)).find("input[type=date]");
    $dates.each(function () {
        var $this = $(this),
            id = $this.attr("id"),
            colName = id.substr(rowid.length + 1),
            cm = $self.jqGrid("getColProp", colName),
            str;
        if ((Modernizr && Modernizr.inputtypes.date) || $this.prop("type") === "date") {
            // convert from iso to newformat
            str = $.jgrid.parseDate.call($this[0], "Y-m-d", $this.val(), cm.formatoptions.newformat);
            $this.attr("type", "text");
            $this.val(str);
        }
    });
};

UPDATE: Explore another demo here, offering enhanced support for Opera 24 and empty input dates.

UPDATE 2: In this modified version of the demo, minor adjustments have been made (specifically setting this for $.jgrid.parseDate) and it utilizes free jqGrid 4.8.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of Angular by implementing nested ng-repeat functionalities:

I am currently working on an ng-repeat feature to add items from the array (album array). Everything seems to be functioning correctly. However, I also have a colors array that should assign different background-colors to the card elements of the album arr ...

Enhancing Numbers with JavaScript

What I'm Looking for: I have 5 counters on my webpage, each starting at 0 and counting upwards to different set values at varying speeds. For example, if I input the values of 10, 25, 1500, 400, and 500 in my variables, I want all counters to reach t ...

The production build encountered an error after upgrading Angular due to a problem with document.documentElement.setAttribute not being recognized

Recently, I updated my application to Angular 16 and the upgrade was successful. The application is running smoothly without any issues. However, when I attempted to run the command for a production build, ng build --configuration=production I encountere ...

What is causing the undefined value to appear?

I'm puzzled as to why the term "element" is coming up as undefined. Even after running debug, I couldn't pinpoint the cause of this issue. Does anyone have any insights on what might be going wrong here? Below is the snippet of my code: const ...

Enhance text search functionality using AngularJS

Just starting to learn angularjs. Below is the code I've written: $scope.styles = [{"name":"walking"},{"name":"Food"},{"name":"culture"}] I have created a checkbox list <div ng-repeat="style in styles"> <input type="checkbox"> {{ ...

Learn the art of closing an AngularJS accordion automatically when another accordion is opened within an AngularJS application

I have encountered an issue with the AngularJS accordion functionality. It seems that when I have multiple accordions, such as accordion-1, accordion-2, and accordion-3, they all open simultaneously if clicked on individually. My main concern is: How can ...

What is the method for individually extracting values from HTML using class li?

Is there a way to extract each value from the HTML within the li class separately? I have tried various methods but none have been successful. Can anyone provide a solution? Here is my JavaScript code: $(document).ready(function() { $(".list-grou ...

Storing the result of an Angular $http.get request in a variable

As a newcomer to Angular, I am exploring how to retrieve a JSON object containing a list of individuals from CouchDB using a $http.get call. The JSON structure includes an id, names, and quotes for each person: { "total_rows": 2, "offset": 0, ...

Using Javascript Reduce to Manipulate Objects

Here is the data I am working with: let info = [ {id: 1, name: "John Doe", type: "A", amount: 100}, {id: 2, name: "Jane Smith", type: "B", amount: 150}, {id: 3, name: "Alice Johnson" ...

I'm looking to automate a system response whenever a user inputs something - how can I achieve this using NodeJS and Socket

I'm looking to create a feature where, if a user enters a specific command, the socket.io will respond with a predefined message. For example: Input: !hi Output: hello! If anyone knows how to achieve this, I'd appreciate some guidance, tha ...

Use jQuery to set a Firebase image as the background of a div element

Is there a way to fetch an image from Firebase and use it as the background for a div element? I've tried several approaches without success. Could someone share some examples on how to achieve this? <div class="museBGSize rounded-corners grpelem" ...

Tips for using the arrow keys to navigate the cursor/caret within an input field

I am trying to create a function that allows the cursor/caret to move inside an input field character by character using the arrow keys (ArrowLeft, ArrowRight) on a keydown event. Current Approach: const handleKeyDown = (e: KeyboardEvent<HTMLInputEle ...

Capturing click events on a stacked area chart with nvd3

Could someone assist me in capturing the click event on a nvd3 stacked area chart? I have successfully managed to capture tooltip show and hide events but am struggling with the click event. How can I obtain information about the clicked point? Please help ...

What are the steps to implement Lazy loading in Node.js?

const posts = await Post.find().populate("receiver").populate("author") try { res.json({ status: true, message: 'All posts fetched', data: posts.reverse() ...

Attempting to change the primary color in Bootstrap is ineffective following a button click

I have been attempting to customize the primary color of Bootstrap 5 using SCSS. Everything works perfectly until I click a button that opens an external link. Below is the content of my SCSS file: $primary: #ae217aff; @import "../node_modules/boots ...

I'm having trouble pinpointing the issue in my code

For some reason, the first button in the div in this code is not working on HTML files. I have tried multiple JavaScript and HTML validators but none of them seem to work. Surprisingly, it works fine on codecademy.com and w3schools.com, but the issue persi ...

The latest update of MS CRM 2013 now includes a version number for WebResources that are of script

I came across an unusual issue in MS CRM 2013 that seems to be intentional, and I need some assistance in finding a workaround for it. The problem is that calling the getScript jQuery method from a WebResource is not possible. In CRM, a version string is ...

JavaScript: locating web addresses in a text

Need help searching for website URLs (e.g. www.domain.com) within a document and converting them into clickable links? Here's how you can do it: HTML: Hey there, take a look at this link www.wikipedia.org and www.amazon.com! JavaScript: (function( ...

How can VueJs effectively update the data fetched using the created function?

When working with the Promise Object, I prefer to utilize the "then" and "catch" functions instead of asynchronous functions for handling responses in a simpler way. This allows me to avoid using await and conditional if-else statements to check the stat ...

Utilizing visual representations for "symbol" within eCharts4r

I have been exploring the use of the "image" option for the symbol parameter in a tree chart with eCharts4r. Despite trying multiple methods, I am struggling to assign a unique image to each node in the tree instead of using a universal one. However, my a ...