How to detect changes in input text field and enable save button

Viewed 2064

I am trying to code a function where it detects changes in the text field and enables the save button.

This is running in Visual Studio 2017, HTML , JavaScript

(function () {


    var customer_address = localStorage.getItem("customer_address");
    var customer_city = localStorage.getItem("customer_city");
    var customer_postal_code = localStorage.getItem("customer_postal_code");



    //Address Section
    function changeAddress() {
        var oldaddress = $("#txtOldAddress").val();
        var newaddress = $("#txtNewAddress").val();


        var url = serverURL() + "/savenewaddress.php";

        var JSONObject = {
            "customer_username": localStorage.getItem("customer_username"),
            "oldaddress": oldaddress,
            "newaddress": newaddress,
        };

        $.ajax({
            url: url,
            type: 'GET',
            data: JSONObject,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (arr) {
                _changeAddressResult(arr);
            },
            error: function () {
                alert("FAIL");
            }
        });
    }

    function _changeAddressResult(arr) {
        if (arr[0].result === 1) {
            /*localStorage.setItem($("#txtNewPassword").val(), customer_username);*/
            alert("OK!")
        }
        else {
            alert("FAIL2");
        }
    }

    //City Section
    function changeCity() {
        var oldcity = $("#txtOldCity").val();
        var newcity = $("#txtNewCity").val();

        var url = serverURL() + "/savenewcity.php";

        var JSONObject = {
            "customer_username": localStorage.getItem("customer_username"),
            "oldcity": oldcity,
            "newcity": newcity,
        };

        $.ajax({
            url: url,
            type: 'GET',
            data: JSONObject,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (arr) {
                _changeAddressResult(arr);
            },
            error: function () {
                alert("FAIL");
            }
        });
    }

    function _changeAddressResult(arr) {
        if (arr[0].result === 1) {
            /*localStorage.setItem($("#txtNewPassword").val(), customer_username);*/
            alert("OK!")
        }
        else {
            alert("FAIL2");
        }
    }

    //Postal Code Section
    function changePostalCode() {
        var oldpostalcode = $("#txtOldPostalCode").val();
        var newpostalcode = $("#txtNewPostalCode").val();

        var url = serverURL() + "/savenewpostalcode.php";

        var JSONObject = {
            "customer_username": localStorage.getItem("customer_username"),
            "oldpostalcode": oldpostalcode,
            "newpostalcode": newpostalcode
        };

        $.ajax({
            url: url,
            type: 'GET',
            data: JSONObject,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (arr) {
                _changeAddressResult(arr);
            },
            error: function () {
                alert("FAIL");
            }
        });
    }

    function _changeAddressResult(arr) {
        if (arr[0].result === 1) {
            /*localStorage.setItem($("#txtNewPassword").val(), customer_username);*/
            alert("OK!")

        }
        else {
            alert("FAIL2");
        }
    }


    //Validation
    $("#ChangeAddressForm").validate({
        rules: {
            txtNewPostalCode: {
                required: true,
                minlength: 6,
                digits: true
            },

            txtNewCity: {
               digits: false
            },
            txtNewAddress: {
                required: true,
                alphanumeric: true
            }

        },
        messages: {
            txtNewAddress: {
                required: "Address is required",
            },
            txtNewCity: {
                required: "City is required",
                digit: "Include only letters!",
            },
            txtNewPostalCode: {
                required: "Postal Code is required!",
                minlength: "Postal Code only contains 6 digits!",
                digits: "Postal Code only contains digits!"
            }
        },
        focusInvalid: false,
        submitHandler: function () {
            return false;
        },
        errorPlacement: function (error, element) {
            error.appendTo(element.parent().parent().after());
        },
    });



    //Save Address Button Function
    $("#btnSaveAddress").bind("click", function () {

        if ($("#ChangeAddressForm").valid()) {
            changeAddress();
            changeCity();
            changePostalCode();



        }
    });

})();

I expect the output to be enabling the submit button when there is changes to the text box in the 3 fields. If there is no changes, then the button will be disabled if the same text exists.

4 Answers

Try this code:

function InputChangeListener(){
  flag = 1;

  var firstInput = document.getElementById("firstInput");
  var secondInput = document.getElementById("secondInput");
  var thirdInput = document.getElementById("thirdInput");

  var firstInputVal = document.getElementById("firstInput").defaultValue;
  var secondInputVal = document.getElementById("secondInput").defaultValue;
  var thirdInputVal = document.getElementById("thirdInput").defaultValue; 



  var submitButton = document.getElementById("submitButton");
   if(firstInput.value == firstInputVal || secondInput.value == secondInputVal || thirdInput.value == thirdInputVal){
       flag = 0;
   }
   if(flag == 1){
      submitButton.style.display = "block"; 
   } else {
      submitButton.style.display = "none"; 
   }
}
#submitButton{
display: none
}
<input id="firstInput" value="test1" type="text" onkeyup ="InputChangeListener()"/><br />
<input id="secondInput" value="test2" type="text" onkeyup ="InputChangeListener()"/><br />
<input id="thirdInput" value="test3" type="text" onkeyup ="InputChangeListener()"/><br />
<input id="submitButton" type="submit" value="Submit" />

You can have a function which is called on each of the input change and then check if all inputs are entered or not.

Example:

<input id = "input1" onchange ="checkIfAllInputsEntered()"/>
<input id = "input2" onchange ="checkIfAllInputsEntered()"/>
<input id = "input3" onchange ="checkIfAllInputsEntered()"/>

JavaScript:

function checkIfAllInputsEntered(){
  flag = 1;
  //get all 3 elements by id's and check their values if they are "" or not
   if(input1 == ""){
       flag = 0;
   }
   if(input2 == ""){
       flag = 0;
   }
   if(input3 == ""){
       flag = 0;
   }

   if(flag == 1)
      //enable button

}

Onchange is usually fired only once input change focus. So you need to use onkeyup event. But you can also add onchange and onkeydown just in case. I assume you are using jQuery. Here is example:


var old1;
var old2;
var old3;

function checkForChange() {
  if (
    old1 != $('#in1').val() ||
    old2 != $('#in2').val() ||
    old3 != $('#in3').val()
  ) {
    $('#save').show();
  }
}
$(function() {
  old1 = $('#in1').val();
  old2 = $('#in2').val();
  old3 = $('#in3').val();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <input id="in1" onchange="checkForChange()" onkeydown="checkForChange()" onkeyup="checkForChange()" value="hello world" /><br/>
  <input id="in2" onchange="checkForChange()" onkeydown="checkForChange()" onkeyup="checkForChange()" value="hello cat" /><br/>
  <input id="in3" onchange="checkForChange()" onkeydown="checkForChange()" onkeyup="checkForChange()" value="hello dog" /><br/>
  <input id="save" value="save" type="submit" style="display:none;" />
</form>

I am trying to code a function where it detects changes in the text field and enables the save button.

First, add the "disabled" attribute in your button tag. Then add an "onchange" event in your button. In js do it like this:

function ontextchanged()
    $('#buttonid').prop('disabled',false);
Related