How can I check if a value is changed on blur event?

前端 未结 10 1207
时光说笑
时光说笑 2021-02-07 06:29

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

10条回答
  •  不思量自难忘°
    2021-02-07 06:55

    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:

    
    

    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');
            }
          }
        }
      });
    

提交回复
热议问题