Sam
Sam

Reputation: 8693

How to check to see if changes have been made to a form

We have a simple form containing several fields, if the user makes any modification we are supposed to show the Save button, else it shouldn't be shown. How do you handle scenarios when a user selects something in a drop down and subsequently goes back to the original value (e.g. from ValA to ValB and then eventually to ValA). How should we handle this in a Rails app.

Upvotes: 2

Views: 549

Answers (2)

Ohgodwhy
Ohgodwhy

Reputation: 50797

EDIT

I've made some updates. It's not the prettiest, but it is late, and this is the best I can do for now.

Helper function was added to evaluate the value and compare against existing value in object. If it exists, we iterate a variable. If the length of the form elements matches the # of occurences of the default value, then we hide the show button. I allowed for 2 arguments in the function, the elements with whom we want to check the values against, and the element at which we wish to toggle the visibility of.

Hopefully this helps.

$(function () {
  var defaults = {},
      eles =  $('form *').filter(':input'),
      btn = $('.submit');
  function checkEmpty(objs, toggle){
    var len = objs.length,
        occurences = 0;
    $.each(objs, function(i,obj){
      if(defaults[i].value == obj.value){
          occurences++;
      }
    });
    if(len == occurences){
        toggle.hide();
    }else{
        toggle.show(); 
    }
  }
  eles.each(function (i, ele) {
    defaults[i] = {
      'id': this.id,
      'value': this.value
    };
  });
  eles.on('keyup propertychange change paste input focusout', function (e) {
    checkEmpty(eles, btn);
  });
});

Your working example

Upvotes: 2

Manivannan Jeganathan
Manivannan Jeganathan

Reputation: 513

I hope jquery-form-observe plugin will meet your requirement. checkout this

http://code.google.com/p/jquery-form-observe/

Upvotes: 1

Related Questions