I want to know if a form has changed at all. The form can contain any form element, such as input, select, textarea etc. Basically I want a way to display to the user that they have unsaved changed made to a form.
How can I do this using jQuery?
To clarify: I want to catch ANY change to the form, not only to input elements but to all other form elements as well, textarea, select etc.
To watch for form data changes in jQuery, we can listen for input changes. And when an input value changes, we add the changed data into the form element object. Then we can listen for changes of the input by writing: $("form :input").
jQuery change() MethodThe change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). The change() method triggers the change event, or attaches a function to run when a change event occurs.
The clone() is an inbuilt method in jQuery which is used to make a copy of selected elements including its child nodes, text and attributes. Syntax: $(selector).clone(true|false) Parameter: It accepts an optional parameter which could be either true or false specifies that event handler should be copied or not.
var $inputsWithSameValue = $('input[value=' + $(this). val() + ']'); hasDuplicates = $inputsWithSameValue.
The approach I usually take in such a case is that I check serialized form value. So the idea is that you calculate initial form state with $.fn.serialize
method. Then when needed you just compare current state with the original serialized string.
To target all input elements (select, textarea, checkbox, input-text, etc.) within a form you can use pseudo selector :input
.
For example:
var $form = $('form'),
origForm = $form.serialize();
$('form :input').on('change input', function() {
$('.change-message').toggle($form.serialize() !== origForm);
});
.change-message {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="change-message">You have unsaved changes.</div>
<div>
<textarea name="description" cols="30" rows="3"></textarea>
</div>
<div>Username: <input type="text" name="username" /></div>
<div>
Type:
<select name="type">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div>
Status: <input type="checkbox" name="status" value="1" /> 1
<input type="checkbox" name="status" value="2" /> 2
</div>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With