Send form only if any input is changed

0

I have a form that opens in a modal bootstrap that is populated dynamically with jquery, this form is enabled for editing, and in this modal has a "Save changes" button, which I want to perform an action only if any field form is changed from the original state, how can I do this?

    
asked by anonymous 26.06.2017 / 07:49

2 answers

1

You can use jQuery serialize .

Through it you can save the state of the form field values when it is loaded. When you submit the form, you can call back and compare to the saved state initially and take whatever action is required.

Here's an example:

var inicial = $("form").serialize();

$("form").on("submit", function(e) {
  e.preventDefault();
  var atual = $("form").serialize();
  if (atual !== inicial) {
    // modificou, pode submeter o form via ajax...
    alert("modificou");
  }
});
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html><head><metacharset="utf-8">
  <title>Demo Formulario</title>
</head>

<body>

  <form>
    <select name="select">
    <option value="">Selecione...</option>
    <option value"1">Item 1</option>
    <option value="2">Item 2</option>
  </select>
    <br>
    <input type="checkbox" name="check" value="check1" id="ch1">
    <label for="ch1">Sim</label>
    <br>
    <input type="radio" name="radio" value="radio1" checked="checked" id="r1">
    <label for="r1">Opção 1</label>
    <input type="radio" name="radio" value="radio2" id="r2">
    <label for="r2">Opção 2</label>
    <br>
    <input name="text">
    <br>
    <br>
    <button type="submit">Enviar</button>
  </form>

</body>

</html>
    
26.06.2017 / 12:58
0

Using sessionStorage to store the initial form, then just compare, it is worth highlighting the use of jQuery serialize ().

$(function () {
                if (sessionStorage) {
                    sessionStorage.setItem('form', jQuery('form').serialize());
                }
                $('#salvar').click(function () {
                    if (jQuery('form').serialize() === sessionStorage.getItem('form')) {
                        alert('Não existe alteração');
                    }else {
                        alert('Existe alteração ');
                    }
                });
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form><inputname="nome" id="nome" type="text">
            <input name="usuario" id="usuario" type="text">
            <input name="email" id="email" type="text">
            <input type="button" value="salvar" id="salvar">
        </form>
    
26.06.2017 / 15:17