Send form only if any input changes

Asked

Viewed 437 times

1

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

  • Can you display part or all of the form’s HTML? and where does the form? via ajax? code come from or the page loads with this information?

2 answers

2

You can use the serialize jQuery.

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

Follow 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>
  <meta charset="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>

1

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

$(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>
            <input name="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.