Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  76] [ 2]  / answers: 1 / hits: 31273  / 10 Years ago, fri, november 7, 2014, 12:00:00

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.


More From » jquery

 Answers
18

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>




[#68878] Wednesday, November 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
giovanny

Total Points: 314
Total Questions: 101
Total Answers: 90

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;