jaclerigo
jaclerigo

Reputation: 567

How to detect which element was changed in form with jQuery

I would like to know if there is any way to detect which element was changed in a form with jQuery. I have a form with about 40 different fields and would like to know which one of them was individually changed. All elements have a different ID. The result should give such an array with the IDs of the elements.

Upvotes: 0

Views: 449

Answers (2)

Olly Hodgson
Olly Hodgson

Reputation: 15775

This sounds like a job for .on() and the change event. This should alert the id and value of any form control when it triggers the change event:

$("#id-of-your-form").on("change", "input, textarea, select", function() {
    var changedInput = $(this);
    alert(changedInput.attr("id"), changedInput.val());
});

I guess you could also add other events like blur, focus and keypress to capture any time the user does anything to the inputs. (e.g. $("#id-of-your-form").on("change blur focus keypress"...)

Upvotes: 1

Barmar
Barmar

Reputation: 780724

Use a change handler that adds the ID to the array.

$(function() {
    var changed = [];
    $(":input").change(function() {
        if (changed.indexOf(this.id) == -1) {
            changed.push(this.id);
        }
    });
});

Upvotes: 5

Related Questions