2

I have one form validator example in java script. In this case, Is there any way to check whether the form is dirty or not?

My platform is JavaScript

Please find corresponding sample below, and suggest any solution.

sample link

code snipet: i have used like:

if (name.value != name.defaultValue) { 
    alert("#name has changed"); 
    }
Kumaresan Sd
  • 1,399
  • 4
  • 16
  • 34

4 Answers4

2

You could use JQuery something like this...

var _isDirty = false;
$("input[type='text']").change(function(){
  _isDirty = true;
});
2

you have tags as kendo-ui-grid and kendo-validator so I suppose you are using kendo framework. if you want to see if the form is dirty you should check the viewModel in kendo way sample.

basically I've created a viewModel which is impements the ObservableObject interface and has a two way binding with the form's container. Every time you change something in the form the change event is fired in the viewModel which set a variable (dirty) as true.

var dirty = false;
var viewModel = new kendo.data.ObservableObject({
    fullname: "test"
});
viewModel.bind("change", function () {
    alert("changed");
    dirty = true;
});
kendo.bind($("#tickets"), viewModel);

Add all the fields you need to "watch" in the ObservableObject and set on their markup the property data-bind="value:fieldName"

simonecosci
  • 1,194
  • 7
  • 13
1

Forms have an input event which acts for all child elements. So you can do:

document.querySelector('#my-form')
  .addEventListener('input', () => {
    // now you know that *something* changed inside
  })
phil294
  • 10,038
  • 8
  • 65
  • 98
0

You need a global boolean variable to remember when you edit anything in your form.

This variable should initially be false, then when the user edits an input, it changes to true. When you submit the form it changes back to false. Now you can check any time you want, whether the dirty variable is true or false.

Example code:

var dirty = false;

var inputs = document.querySelectorAll('input');
for (var i = 0;i < inputs.length)
{
    var input = inputs[i];
    input .addEventListener('input', function()
    {
        dirty = true;
    });
}

var form = document.forms[0];
form.addEventListener('submit, function()
{
    dirty = false;
}
Poul Bak
  • 10,450
  • 5
  • 32
  • 57