Search code examples
javascriptjqueryalpacajs

How to identify alpacajs field element is changed or modified?


I am new to alpacajs. I have alpacajs form and also have save button for alpacajs from. More than that i have previous and next button. I currently plan to develop something like below.

For example if someone come to the alpacajs form page and if they modified some fields in form then without save they can't allow to go previous/ next so i want to disable those button. If they save the form after the modification then they can go previous/ next so i want to enable those button.

How to do this with jquery and in alpacajs?


Solution

  • If you want to save the form data as draft form in your alpaca form you have only to add the Save as draft button next to your submit and put some logic to it.

    So alpaca will handle the click event on that button, but not for Previous / Next buttons. These buttons stays out of alpaca config, and they handle only page navigation.

    To add a new button to your alpaca form

    "form": {
      "buttons": {
        "save": {
          "title": "Save draft",
          "click": function() {
            var value = this.getValue();
            // call backend service to save the form as draft
            $.ajax({
              method: "POST",
              url: "https://httpbin.org/post", // backend webservice
              data: value // form data
             })
            .done(function(data) {
              // check some backend response code or some flag
              // with some conditions activate next and previous buttons
              $("#previousBtn").prop('disabled', false);
              $("#nextBtn").prop('disabled', false);
            })
          }
        },
        "submit": {
          "click": function() {
            var value = this.getValue();
            alert(JSON.stringify(value, null, "  "));
          }
        }
      }
    }
    

    Don't forget to call some other webservice to get the draft data for that form if there's any and initialize alpaca data config like this:

    // data initialization - here you can call a service to get draft data for this form
    data = {
       username: "test"
    };
    
    $("#form").alpaca({
       "data": data, // draft data if there's any
       "schema": {
         // alpaca schema config
       }
    }
    

    Here's a working fiddle for this.