Joe C
Joe C

Reputation: 2834

How to detect HTML form changes using jQuery, in detail for a noob?

I'm kind of a noob on HTML. I've sifted thru this, this, this, this, and more. Here's the code I came up with but it, and many more experiments I've done, do not work. I can pound on my input fields all day and I never see the alert. Most answers assume you know something that I guess I don't know. Can anyone tell me what may be wrong?

<script   
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
    $("#myform :input").change(function() {
        alert("Form changed");
    });
</script>

<form id="myform" name="myform" method="GET">
   <!-- a bunch of text fields, etc -->
</form>

Upvotes: 1

Views: 6550

Answers (2)

Jason Lemrond
Jason Lemrond

Reputation: 417

<form id="myform" name="myform" method="GET">
    <input type="text" name="field">
    <input type="text" name="field2">
    <input type="text" name="field3">
</form>

<script>
    $("#myform input").change(function() {
        alert("Form changed");
    });
</script>

Try this. Make sure your script is below the form or the form won't be loaded when the script runs. Or you could wrap your javascript in $(document).ready(). This will execute your code once the DOM is loaded. https://api.jquery.com/ready/

$(document).ready(function() {
    // Your Javascript
}

Also, if you are looking for the alert to fire on each keypress, take a look at keyup() or keydown() instead of using change() in jQuery: https://api.jquery.com/keyup/

Upvotes: 4

JanR
JanR

Reputation: 6130

This explains it very clearly. Generic way to detect if html form is edited

You add a data attribute to the form: data-changed="false"

<script   
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
    $("#myform :input").change(function() {
       //here we make sure that the on change event for every form input element
       //triggers the flag on the form (data-changed) to true.
       $("#myform").data("changed",true);
    });

    //when the form is being submitted:
    $(document).on('submit',"#myform",function(){
        if ($("#myform").data("changed")) {
        {
           //something has changed: do something
        }
    })
</script>

<form id="myform" name="myform" method="GET" data-changed="false">
   <!-- a bunch of text fields, etc -->
</form>

Upvotes: 0

Related Questions