Question

Basically I need to check if the value is changed in a textbox on the 'blur' event so that if the value is not changed, I want to cancel the blur event.

If it possible to check it the value is changed by user on the blur event of an input HTML element?

Was it helpful?

Solution

I don't think there is a native way to do this. What I would do is, add a function to the focus event that saves the current value into a variable attached to the element (element.oldValue = element.value). You could check against that value onBLur.

OTHER TIPS

You can't cancel the blur event, you need to refocus in a timer. You could either set up a variable onfocus or set a hasChanged variable on the change event. The blur event fires after the change event (unfortunately, for this situation) otherwise you could have just reset the timer in the onchange event.

I'd take an approach similar to this:

(function () {
    var hasChanged;
    var element = document.getElementById("myInputElement");
    element.onchange = function () { hasChanged = true; }
    element.onblur = function () {
        if (hasChanged) {
            alert("You need to change the value");

            // blur event can't actually be cancelled so refocus using a timer
            window.setTimeout(function () { element.focus(); }, 0);          
        }
        hasChanged = false;
    }
})();

Within the onblur event, you can compare the value against the defaultValue to determine whether a change happened:

<input onblur="if(this.value!=this.defaultValue){alert('changed');}">

The defaultValue will contain the initial value of the object, whereas the value will contain the current value of the object after a change has been made.

References:

value vs defaultValue

Using Jquery events we can do this logic

Step1 : Declare a variable to compare the value

var  lastVal ="";

Step 2: On focus get the last value from form input

  $("#validation-form :input").focus(function () {
                 lastVal = $(this).val();

  });

Step3:On blur compare it

$("#validation-form :input").blur(function () {
                 if (lastVal != $(this).val())
                 alert("changed");
             });

You can use this code:

var Old_Val;
var Input_Field = $('#input');

Input_Field.focus(function(){
     Old_Val = Input_Field.val();
});

Input_Field.blur(function(){
    var new_input_val = Input_Field.val();
    if (new_input_val != Old_Val){
          // execute you code here
    }
});

I know this is old, but I figured I'd put this in case anyone wants an alternative. This seems ugly (at least to me) but having to deal with the way the browser handles the -1 index is what was the challenge. Yes, I know it can be done better with the jquery.data, but I'm not that familiar with that just yet.

Here is the HTML code:

<select id="selected">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>

Here is the javascript code:

var currentIndex; // set up a global variable for current value

$('#selected').on(
  { "focus": function() { // when the select is clicked on
      currentIndex = $('#selected').val(); // grab the current selected option and store it
      $('#selected').val(-1); // set the select to nothing 
    }
  , "change": function() { // when the select is changed
      choice = $('#selected').val(); // grab what (if anything) was selected
      this.blur(); // take focus away from the select
      //alert(currentIndex);
      //setTimeout(function() { alert(choice); }, 0);
    }
  , "blur": function() { // when the focus is taken from the select (handles when something is changed or not)
      //alert(currentIndex);
      //alert($('#selected').val());
      if ($('#selected').val() == null) { // if nothing has changed (because it is still set to the -1 value, or null)
        $('#selected').val(currentIndex); // set the value back to what it originally was (otherwise it will stay at what was newly selected)
      } else { // if anything has changed, even if it's the same one as before
        if ($('#selected').val() == 2) { // in case you want to do something when a certain option is selected (in my case, option B, or value 2) 
            alert('I would do something');
        }
      }
    }
  });

Something like this. Using Kevin Nadsady's above suggestion of

this.value!=this.defaultValue

I use a shared CSS class on a bunch of inputs then do:

    for (var i = 0; i < myInputs.length; i++) {
        myInputs[i].addEventListener('blur', function (evt) {
            if(this.value!=this.defaultValue){
                //value was changed now do your thing
            }
        });
        myInputs[i].addEventListener('focus', function (evt) {
            evt.target.setAttribute("value",evt.target.value);
        });
    }

Even if this is an old post, I thought i'd share a way to do this with simple javascript.

The javascript portion:

<script type="text/javascript">
function HideLabel(txtField){
	    if(txtField.name=='YOURBOXNAME'){
	        if(txtField.value=='YOURBOXNAME')
	            txtField.value = '';
	        else
	            txtField.select();
	        
	    }
	}
	function ShowLabel(YOURBOXNAME){
	    if(txtField.name=='YOURBOXNAME'){
	        if(txtField.value.trim()=='')
	            txtField.value = 'YOURDEFAULTVALUE';
	    }
	}
</script>

Now the text field in your form:

<input type="text" id="input" name="YOURBOXNAME" value="1" onfocus="HideLabel(this)" 
onblur="ShowLabel(this)">
And bewn! No Jquery needed. just simple javascript. cut and paste those bad boys. (remember to put your javascript above the body in your html)

Similar to @Kevin Nadsady's post, the following will work in native JS functions and JQuery listener events. Within the onblur event, you can compare the value against the defaultValue:

 $(".saveOnChange").on("blur", function () {
     if (this.value != this.defaultValue) {
         //Set the default value to the new value
         this.defaultValue = this.value;
         //todo: save changes
         alert("changed");
     }
 });

Why not just maintaining a custom flag on the input element?

input.addEventListener('change', () => input.hasChanged = true);
input.addEventListener('blur', () => 
{
    if (!input.hasChanged) { return; }
    input.hasChanged = false;
    // Do your stuff
});

https://jsfiddle.net/d7yx63aj

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top