Detect Input Data Changed by jQuery

This is the technique to check our data input whether they are changed or not before sending them to the database via ajax.

This function will help you to save your ajax request time if there is nothing changed in your data input. So, when you did not change anything in your form input, this function will check and return you back an value (true/false). In this case, if you can stop your ajax requesting to update the exactly the same data to your database.

For more detail, please see the bellow instruction.

INSTRUCTION

You can use this script in your working file or external JavaScript file.
function detectTextChanged(elementName,dataName){
if($.type(elementName)!='string' || $.type(dataName)!='string'){return '';}
var elementType_sign = elementName.substring(0,1);
var result = false;			
if(elementType_sign=='.'){
$(elementName).each(function() {
if($.trim($( this ).val()) != $.trim($( this ).data(dataName))){result = true;}
});	
}else if(elementType_sign=='#'){
if($.trim($(elementName).val()) != $.trim($(elementName).data(dataName))){result = true;}
}
return result;
}

With this function, you can customize your desired element name (ID or Class) and its data attribute name.
<input type="text" class="mytext" data-inidata="mydata"  value="mydata"/>

Now we use class name mytext and data attribute name inidata with its value. The value of data-inidata is used for verifying the change of the text in that input.
detectTextChanged('.mytext','inidata')

The above script calls the function and will return the value true if data has changed and false if data has not changed.

Similar Tutorials

Comments