Javascript to reset a value to previous value if user leave it blank

I’m using devExtreme to make a table of open vehicle maintenance tickets. When I click the edit button it opens up a page where I can edit various fields. One of those fields is the mileage. The problem I’m having is that if the user deletes the mileage and leaves it blank (shouldn’t happen, but obviously we want to cover all our bases), they can’t save without putting something in there. What we want is for it to put the previous value back in if they save without putting a new value in there. I’m not familiar with javascript much, but from what I’ve been able to find, it sounds like this is my only real option. Any ideas on how to do this?
I have attached the code for the page, however I’m not sure how much help it will be because the devExtreme translates pretty messy when it’s live. Below the page source is the code I have posted that is the actual code in the IDE. This is an asp.net mvc project, using devExtreme.

Live source code:

<div id="ticketsTable">
    <script>DevExpress.config({"serverDecimalSeparator":"."});DevExpress.aspnet.setTemplateEngine();</script><div id="gridContainer"></div><script type="text/html" id="gridContainer-columns15-cellTemplate"><a href="/Home/Comments?ticketId=<%= data.Id %>">View</a></script><script>jQuery(function($){$("#gridContainer").dxDataGrid({"paging":{"enabled":true},"wordWrapEnabled":true,"editing":{"mode":"form","allowUpdating":true},"headerFilter":{"visible":true},"columns":[{"dataField":"Id","dataType":"number","validationRules":[{"type":"required","message":"The Id field is required."}],"caption":"Ticket#","allowEditing":false,"width":80.0},{"dataField":"LocationId","dataType":"number","validationRules":[{"type":"required","message":"The LocationId field is required."}],"caption":"Location","width":105.0,"lookup":{"dataSource":{"store":DevExpress.data.AspNet.createStore({"key":"Id","loadUrl":"/Home/GetLocations"})},"displayExpr":"Name","valueExpr":"Id","allowClearing":false}},{"dataField":"DepartmentId","dataType":"number","validationRules":[{"type":"required","message":"The DepartmentId field is required."}],"caption":"Department","width":105.0,"lookup":{"dataSource":{"store":DevExpress.data.AspNet.createStore({"key":"Id","loadUrl":"/Home/GetDepartment"})},"displayExpr":"Name","valueExpr":"Id","allowClearing":false}},{"dataField":"CreateDate","dataType":"date","validationRules":[{"type":"required","message":"The CreateDate field is required."}],"caption":"Date Created","width":90.0,"allowEditing":false},{"dataField":"AssociatedAssetId","dataType":"number","caption":"Asset Tag","width":105.0,"lookup":{"dataSource":{"store":DevExpress.data.AspNet.createStore({"key":"Id","loadUrl":"/Assets/GetAssets"})},"displayExpr":"AssetTag","valueExpr":"Id"}},{"dataField":"TicketTypeId","dataType":"number","caption":"Ticket Type","width":100.0,"lookup":{"dataSource":{"store":DevExpress.data.AspNet.createStore({"key":"Id","loadUrl":"/Home/GetTicketType"})},"displayExpr":"Type","valueExpr":"Id"}},{"dataField":"AssetTypeId","dataType":"number","caption":"Asset Type","width":100.0,"lookup":{"dataSource":{"store":DevExpress.data.AspNet.createStore({"key":"Id","loadUrl":"/Home/GetAssetType"})},"displayExpr":"Type","valueExpr":"Id"}},{"dataField":"AssignedDate","dataType":"date","caption":"Date Assigned","allowEditing":false,"visible":false},{"dataField":"AssignToId","dataType":"string","caption":"Assigned To","width":105.0,"lookup":{"dataSource":{"store":DevExpress.data.AspNet.createStore({"loadUrl":"/Home/GetAssignedToName"})},"displayExpr":"FullName","valueExpr":"Id"}},{"dataField":"RequestedByName","dataType":"string","caption":"Requested By","visible":false,"allowEditing":false},{"dataField":"AssociatedAsset.MeterUnitsId","dataType":"number","caption":"Meter Type","visible":false,"allowEditing":false,"lookup":{"dataSource":{"store":DevExpress.data.AspNet.createStore({"key":"Id","loadUrl":"/Assets/GetMeterUnits"})},"displayExpr":"Type","valueExpr":"Id","allowClearing":false}},{"dataField":"AssociatedAsset.CurrentMeterReading","dataType":"number","validationRules":[{"type":"required","message":"The CurrentMeterReading field is required."}],"caption":"Meter Reading","visible":false,"formItem":{"isRequired":false}},{"dataField":"ClosedDate","dataType":"date","formItem":{"visible":false},"caption":"Date Closed","allowEditing":false,"visible":false},{"dataField":"StatusId","dataType":"number","caption":"Status","width":100.0,"lookup":{"dataSource":{"store":DevExpress.data.AspNet.createStore({"key":"Id","loadUrl":"/Home/GetStatus"})},"displayExpr":"Status1","valueExpr":"Id","allowClearing":false}},{"dataField":"Description","dataType":"string","formItem":{"editorOptions":{"height":140.0},"editorType":"dxTextArea"},"allowEditing":true,"visible":false},{"formItem":{"visible":false},"dataField":"Id","caption":"Comments","width":105.0,"cellTemplate":$("#gridContainer-columns15-cellTemplate")}],"dataSource":{"store":DevExpress.data.AspNet.createStore({"key":"Id","loadUrl":"/Home/GetTickets","updateUrl":"/Home/Put"})}});});</script>
</div>

<div id="buttonGroup">
    <div id="btnPrint"></div><script>jQuery(function($){$("#btnPrint").dxButton({"icon":"print","text":"Print","elementAttr":{"class":"row-element"}});});</script>
</div>

<script>
    $(function () {
        $("#btnPrint").click(function () {
            var contents = $("#ticketsTable").html();
            var frame1 = $('<iframe />');
            frame1[0].name = "frame1";
            frame1.css({ "position": "absolute", "top": "-1000000px" });
            $("body").append(frame1);
            var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
            frameDoc.document.open();
            //Create a new HTML document.
            frameDoc.document.write('<html><head><title>DIV Contents</title>');
            frameDoc.document.write('</head><body>');
            //Append the external CSS file.
            frameDoc.document.write('<link href="style.css" rel="stylesheet" type="text/css" />');
            //Append the DIV contents.
            frameDoc.document.write(contents);
            frameDoc.document.write('</body></html>');
            frameDoc.document.close();
            setTimeout(function () {
                window.frames["frame1"].focus();
                window.frames["frame1"].print();
                frame1.remove();
            }, 500);
        });
    });

</script>


IDE code:

@using Maintenance.BusinessLogic.Model
@model HomeViewModel
    <div id="title">
        <h1>Open Tickets</h1>
    </div>

<div id="ticketsTable">
    @(Html.DevExtreme().DataGrid<Ticket>()
          .ID("gridContainer")
          .Paging(paging => paging.Enabled(true))
          .WordWrapEnabled(true)
          .Editing(editing =>
          {
              editing.Mode(GridEditMode.Form);
              editing.AllowUpdating(true);
          })

          .HeaderFilter(f => f.Visible(true))
          .Columns(columns =>
          {
              columns.AddFor(m => m.Id).Caption("Ticket#").AllowEditing(false)
                  .Width(80);

              columns.AddFor(m => m.LocationId)
                  .Caption("Location")
                  .Width(105)
                  .Lookup(lookup => lookup
                      .DataSource(d => d.Mvc().Controller("Home").LoadAction("GetLocations").Key("Id"))
                      .DisplayExpr("Name")
                      .ValueExpr("Id")
                      .AllowClearing(false)
                  );

              columns.AddFor(m => m.DepartmentId)
                  .Caption("Department")
                  .Width(105)
                  .Lookup(lookup => lookup
                      .DataSource(d => d.Mvc().Controller("Home").LoadAction("GetDepartment").Key("Id"))
                      .DisplayExpr("Name")
                      .ValueExpr("Id")
                      .AllowClearing(false)
                  );

              columns.AddFor(m => m.CreateDate).Caption("Date Created").Width(90).AllowEditing(false);

              columns.AddFor(m => m.AssociatedAssetId)
                  .Caption("Asset Tag")
                  .Width(105)
                  .Lookup(lookup => lookup
                      .DataSource(d => d.Mvc().Controller("Assets").LoadAction("GetAssets").Key("Id"))
                      .DisplayExpr("AssetTag")
                      .ValueExpr("Id")
                  );

              columns.AddFor(m => m.TicketTypeId)
                  .Caption("Ticket Type")
                  .Width(100)
                  .Lookup(lookup => lookup
                      .DataSource(d => d.Mvc().Controller("Home").LoadAction("GetTicketType").Key("Id"))
                      .DisplayExpr("Type")
                      .ValueExpr("Id")
                  );

              columns.AddFor(m => m.AssetTypeId)
                  .Caption("Asset Type")
                  .Width(100)
                  .Lookup(lookup => lookup
                      .DataSource(d => d.Mvc().Controller("Home").LoadAction("GetAssetType").Key("Id"))
                      .DisplayExpr("Type")
                      .ValueExpr("Id")
                  );

              columns.AddFor(m => m.AssignedDate).Caption("Date Assigned").AllowEditing(false).Visible(false);

              columns.AddFor(m => m.AssignToId)
                  .Caption("Assigned To")
                  .Width(105).DataType(GridColumnDataType.String)
                  .Lookup(lookup => lookup
                      .DataSource(d => d.Mvc().Controller("Home").LoadAction("GetAssignedToName"))
                      .DisplayExpr("FullName")
                      .ValueExpr("Id")
                  );

              columns.AddFor(m => m.RequestedByName)
                  .Caption("Requested By")
                  .Visible(false)
                  .AllowEditing(false);

              columns.AddFor(m => m.AssociatedAsset.MeterUnitsId)
                  .Caption("Meter Type")
                  .Visible(false)
                  .AllowEditing(false)
                  .Lookup(lookup => lookup
                      .DataSource(d => d.Mvc().Controller("Assets").LoadAction("GetMeterUnits").Key("Id"))
                      .DisplayExpr("Type")
                      .ValueExpr("Id")
                      .AllowClearing(false)
                  );
                                                          **This is where the problem is! I need a script that can put the CurrentMeterReading back in place in the case of an empty value on save!**
              columns.AddFor(m => m.AssociatedAsset.CurrentMeterReading).Caption("Meter Reading").Visible(false).FormItem(a => a.IsRequired(false));


              columns.AddFor(m => m.ClosedDate)
              .FormItem(x => x.Visible(false))
              .Caption("Date Closed")
              .AllowEditing(false)
              .Visible(false);

              columns.AddFor(m => m.StatusId)
                  .Caption("Status")
                  .Width(100)
                  .Lookup(lookup => lookup
                      .DataSource(d => d.Mvc().Controller("Home").LoadAction("GetStatus").Key("Id"))
                      .DisplayExpr("Status1")
                      .ValueExpr("Id")

                      .AllowClearing(false)
                  );

              columns.AddFor(m => m.Description)
                  .FormItem(m => m.Editor(e => e.TextArea().Height(140)))
                  .AllowEditing(true)
                  .Visible(false);

              columns.Add()
                  .FormItem(x => x.Visible(false))
                  .DataField("Id")
                  .Caption("Comments")
                  .Width(105)
                  .CellTemplate(@<text><a href="@Url.Action("Comments","Home")?ticketId=<%= data.Id %>">View</a></text>);
          })
          .DataSource(d => d.Mvc()
              .Controller("Home")
              .LoadAction("GetTickets")
              .UpdateAction("Put")
              .Key("Id")
          )
          )
</div>

<div id="buttonGroup">
    @( Html.DevExtreme().Button()
        .ID("btnPrint")
           .Icon("print")
           .Text("Print")
           .ElementAttr("class", "row-element")
          )
</div>

<script>
    $(function () {
        $("#btnPrint").click(function () {
            var contents = $("#ticketsTable").html();
            var frame1 = $('<iframe />');
            frame1[0].name = "frame1";
            frame1.css({ "position": "absolute", "top": "-1000000px" });
            $("body").append(frame1);
            var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
            frameDoc.document.open();
            //Create a new HTML document.
            frameDoc.document.write('<html><head><title>DIV Contents</title>');
            frameDoc.document.write('</head><body>');
            //Append the external CSS file.
            frameDoc.document.write('<link href="style.css" rel="stylesheet" type="text/css" />');
            //Append the DIV contents.
            frameDoc.document.write(contents);
            frameDoc.document.write('</body></html>');
            frameDoc.document.close();
            setTimeout(function () {
                window.frames["frame1"].focus();
                window.frames["frame1"].print();
                frame1.remove();
            }, 500);
        });
    });

</script>

Well this would probably be more easily/reliably handled at the asp end than the javascript end, especially as your code as listed doesn’t actually restrict mileage as being required… but the answer’s gonna be somewhere along the lines of $('someidentifier').change(function(e) { if ($(this).val() == "") { $(this).val(theoldvalues.mileage); } });

Thanks I’ll try this. Unfortunately I can’t do this on the asp.net side because the devExtreme is catching it before I can even fire to a controller.

Also, I should mention that while I have in the code set the meter reading requirement to false, the code is not responding to that. I have since removed it.

Pretending I don’t know anything about javascript, because I don’t, what goes in the area of ‘someidentifier’? Can I do a named function so that I can call it where I need to? Also, for the theoldvalues.mileage, can I change that to m => m.AssociatedAsset.CurrentMeterReading ? I’m just not understanding this. I tried using this script, I even tried modifying it several times to fit my needs and looking around online but nothing with javascript seems to make much sense.

I think of them as “CSS selector”.

I see. So the problem with that is because I’m using devExtreme, I don’t have anything like that.

columns.AddFor(m => m.AssociatedAsset.CurrentMeterReading.Caption("Meter Reading").Visible(false);

The above is what i’m working with. And below this is what it looks like when I try to put in a named function:

columns.AddFor(m => m.AssociatedAsset.CurrentMeterReading).SetCellValue(resetMeterReading).Caption("Meter Reading").Visible(false);

And this is what the modified version of @m_hutley 's javascript looks like:

function resetMeterReading() { if ($(this).val() == "") { $(this).val(m => m.AssociatedAsset.CurrentMeterReading); } };

Maybe I’m off on the function, I just went based on what I was finding online. I have no idea if this is anywhere near useable code.

The answer to your questions are “I dont know” and “I dont know”.
I dont know what your script spits out at the end.
I dont know what values your system uses. The IDE code is jibberish to me, because its not standardized Javascript. It’s not even Javascript, its some form of preprocessor language all their own.

Ok, well thanks for trying, but I’m looking for constructive answers. if you don’t know, there’s not much use in responding. Thanks anyways.

Update: I was able to fix this. On .SetCellValue(resetMeterReading), I didn’t realize that the parameter needed to be a string, so when I changed it to .SetCellValue(“resetMeterReading”) it worked!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.