简体   繁体   中英

jquery check if text has been deleted from input field

I am using bootstrap typeahead. When a user enters an address into a form, a dropdown displays with possible addresses. When they select one, I add a hidden input field with the id of the address from database.

Now when the user removes texts from the input field, well that address is no longer valid, so I want to remove that hidden input field. The problem is how do I detect when a user deletes text from the input field using delete key or using mouse.

I've already tried keypress event, it does not work when using delete key:

var input_changed = false
$('#myid').bind('typeahead:selected', function(obj, datum, name) {
    $.ajax({
        url: "/lead_profiles/populate_address",
        data: {
            address : datum
        }
        // dataType: "script"
    }).done(function(data){
        var contact = JSON.parse(data)[0];
        var $parent = $("#myid").closest(".form-group");
        $parent.after('<input name="lead_profile[contact_attributes][id]" type="hidden" value="' + contact.id + '">')
        input_changed = true
    });
});

$("#myid").on('keypress', function(){
  if(input_changed){
      alert("Input has changed");
  }
})

I need another event besides keypress to determine if text has been removed from input field.

You can use oninput event: { 'keyup paste' for older browsers which don't support it }

$("#myid").on('input', function(){
  if(input_changed){
      alert("Input has changed");
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM