20

Here's the code I am using:

$('form').bind('keyup change', function(){

The submit button is set to DISABLED by default, if something changes inside a input text field, or radio button check state or drop-down selection value, then the button must be set ENABLED by removing the disabled attribute.

My END GOAL: enter image description here

EDIT: If anything is changed back to its default value, the submit button shall be set to disabled by prop('disabled', true); - need some method to keep track of every change.

====================================================

Example: Go to Twitter, and sign-in, from the drop-down menu select Settings. In the Account Page, change your Username (just add an extra char), next scroll down, set a checkbox to checked, and change your country choice.

The button will be enabled at the bottom, go back and uncheck the checkbox you previously checked, the button at the bottom will remain enabled,

scroll to the top change your UserName back to what it was, scroll down the button to save changes will still be enabled, go to the country list and changed it back to what you previously had, now finally scroll down: the save changes button will be disabled.

====================================================

EDIT: this seems very similar, What is the best way to track changes in a form via javascript?

Quote: "You can render it disabled by default and have JavaScript handlers watching the inputs for change events to enable it. Maybe render some hidden fields or directly render JavaScript values to store the "originals" and, on those change events, check the current values against the originals to determine if the button should be enabled or disabled. – David Jan 18 at 15:14" (Enable 'submit' button only if a value in the form has been changed).

5
  • Do you want to use default value like carl or johnson? how about a placeholder?
    – PSL
    May 16, 2013 at 17:01
  • 1
    @PSL: Not the default there, here's how: First Name: Erik, gets changed to something else, the button is then set to ENABLED, but if the user goes back and changes first name to Erik - as it was from beginning the button should become disabled, since he never made a change. The default values are just added for the sake of this demo.
    – John Smith
    May 16, 2013 at 17:04
  • 1
    The default values can actually be anything, since they are loaded form a database....
    – John Smith
    May 16, 2013 at 17:05
  • how about having a data-default attribute that holds the default values - then check on change/keyup of the inputs if any of the current values have been changed?
    – wirey00
    May 16, 2013 at 17:50
  • @JohnSmith I just needed to do the same thing. It only takes a few lines of code to achieve. stackoverflow.com/a/24790754/1850421
    – user1850421
    Jul 16, 2014 at 21:11

5 Answers 5

66

I know this is a late answer, but this method uses far less code than the accepted answer without needing IDs on fields and without storing a global array.

Simply use .serialize() to store the data and check if it matches on each change.

http://jsfiddle.net/Pug3H/2/

$('form')
    .each(function(){
        $(this).data('serialized', $(this).serialize())
    })
    .on('change input', function(){
        $(this)             
            .find('input:submit, button:submit')
                .prop('disabled', $(this).serialize() == $(this).data('serialized'))
        ;
     })
    .find('input:submit, button:submit')
        .prop('disabled', true)
;
4
  • FYI, this has one drawback: If you have custom widgets that put JSON data in hidden fields you have string comparisons on the JSON data. so {"foo": "bar"} and {"foo":"bar"} are different strings even though they are the same value. Sep 29, 2016 at 11:11
  • 1
    Hello. If I want to check change on only the <textarea> how can I achieve that? May 13, 2018 at 5:13
  • The input[type="image"] can be also added to list of selectors that perform submission. w3schools.com/tags/att_input_type_image.asp
    – Amr
    Mar 22, 2020 at 10:38
  • Great, but this doesn't enable the submit button when input file has changed. Jul 1, 2020 at 10:49
13

You just need to save the orignal values and then check against them after every change.

Example: http://jsfiddle.net/justincook/42EYq/15/

JavaScript:

// Store original values
var orig = [];             
$("form :input").each(function () {
    var type = $(this).getType();
    var tmp = {'type': type, 'value': $(this).val()};
    if (type == 'radio') { tmp.checked = $(this).is(':checked'); }
    orig[$(this).attr('id')] = tmp;
});

// Check values on change
$('form').bind('change keyup', function () {
    var disable = true;
    $("form :input").each(function () {
        var type = $(this).getType();
        var id = $(this).attr('id');    
        if (type == 'text' || type == 'select') {
            disable = (orig[id].value == $(this).val());
        } else if (type == 'radio') {
            disable = (orig[id].checked == $(this).is(':checked'));
        }    
        if (!disable) { return false; } // break out of loop
    });

    $('#submit-data').prop('disabled', disable); // update button
});

// Get form element type
$.fn.getType = function () { 
    if(this[0].tagName == "INPUT")
        return $(this[0]).attr("type").toLowerCase() 
    else
        return this[0].tagName.toLowerCase();        
}

HTML:

<form id="" action="" method="post">
    <input type="text" value="Carl" name="firstname" id="firstname" />
    <input type="text" value="Johnson" name="lastname" id="lasttname" />
    <input id="radio_1" type="radio" value="female" name="sex" />Female
    <input id="radio_2" type="radio" value="male" name="sex" />Male
    <select id="country-list" name="countries">
        <option value="xx" selected="">Worldwide</option>
        <option value="in">India</option>
        <option value="us">United States</option>
    </select>
    <button id="submit-data" disabled="" type="submit">Save changes</button>
</form>
7
  • In my code HTML file, I just pasted in your solution, and it does not work perfectly, as I expect it, in the fiddle it does however. :(
    – John Smith
    May 16, 2013 at 18:33
  • 1
    The only change I made to your HTML was adding an ID to your radio fields. Add those if you haven't already. If it is still not working, see if you are getting an error in the JavaScript console (ctrl+shift+j in Chrome).
    – Justin
    May 16, 2013 at 18:37
  • 1
    If you are using php, you can just put <?php echo uniqid() ?> in the ID field.
    – Justin
    May 16, 2013 at 18:43
  • 3
    There is a much easier way to do this using serialize
    – user1850421
    Jul 16, 2014 at 21:01
  • 1
    Yes, I like your serialize method below as it doesn't require the extra work to get the input type. Very clever.
    – Justin
    Jul 17, 2014 at 4:25
4

An improved version of @Nigel Angel answer:

/* Disable the forms submissions until they have changed */
$(window).on('load', function (e) {
    $('form').each(function(){
        $(this).data('serialized', $(this).serialize())
    })
    .on('change input', function(){
        $(this).find(':submit, input[type="image"]')
            .prop('disabled', $(this).serialize() == $(this).data('serialized'));

        /* Check if input with type files has changed */
        var changedFiles = $( ":file" ).filter(function( index ) {
            return this.value != this.defaultValue;
        }).length;

        if ( changedFiles > 0) {
            $(this).find(':submit, input[type="image"]')
                .prop('disabled', false);
        }
    })
    .find(':submit, input[type="image"]').prop('disabled', true);
});

  • Added the input[type="image"] to the list of selectors that perform submission.
  • Added a check for changes of input with type file.
  • Also shortened the answer to use :submit to cover both cases of button and input.
1

You can add a data-attribute to hold the default values - for checked types you can use 0 for unchecked and 1 for checked

<form id="" action="" method="post">
    <input type="text" data-default="Carl" value="Carl" name="firstname" id="firstname" />
    <input type="text" data-default="Johnson" value="Johnson" name="lastname" id="lasttname" />
    <br />
    <br />
    <input id="female" type="radio" value="female" name="sex" data-default="0" />Female
    <br />
    <input id="male" type="radio" value="male" name="sex" data-default="0" />Male
    <br />
    <br />
    <select id="country-list" name="countries" data-default="xx">
        <option value="xx" selected="">Worldwide</option>
        <option value="in">India</option>
        <option value="il">Israel</option>
        <option value="ru">Russia</option>
        <option value="us">United States</option>
    </select>
    <br />
    <br />
    <button id="submit-data" disabled="" type="submit">Save changes</button>
</form>

then in for your jquery use filter to get the ones that changed

var button = $('#submit-data');
$('form :input').not(button).bind('keyup change', function () {
    // get all that inputs that has changed
    var changed = $('form :input').not(button).filter(function () {
        if (this.type == 'radio' || this.type == 'checkbox') {
            return this.checked != $(this).data('default');
        } else {
            return this.value != $(this).data('default');
        }
    });
    // disable if none have changed - else enable if at least one has changed
    $('#submit-data').prop('disabled', !changed.length);
});

FIDDLE

0

I tried this code:

$('.form_contact')
.each(function(){
$(this).data('serialized', $(this).serialize())})
.on('change input', function(){
$(this)
.find('button:reset, button:submit')
.attr('disabled', $(this).serialize() == $(this).data('serialized'));})
.find('button:reset, button:submit')
.attr('disabled', true);

And it works perfectly on text input and textarea and select. But when I upload a picture for example with the following input:

<input type="file" name="thumbnail" id="thumbnail" class="thumbnail-input__input" onchange="preview()" accept=".png,.jpg,.jpeg,.webp" data-file- input>

The image appears and everything is fine, but the buttons do not become active and remain disabled, does anyone have any idea what can be done to make it work?

4
  • Hi, you should post your own question and referring this one.
    – Thomas
    Feb 20 at 15:24
  • @Thomas That's what I did Feb 20 at 15:28
  • No, you posted a answer on that question, not a new one.
    – Thomas
    Feb 20 at 15:31
  • @Thomas Obviously, how can I answer what I'm asking because I don't know, I didn't understand.. Feb 20 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.