javascriptjquerysafaritwitter-flight

Safari issue with text inputs, text is selected as user enters it causing text to be lost


I have the following input element on my page:

<input class="input" name="custom_fields[new]" placeholder="Enter placeholder" type="text">

I have a Twitter Flight event listener on this element that looks like this:

this.on('keyup', {
  inputsSelector: this.updateViewInputs
});

Which triggers this method:

this.updateViewInputs = function(ev) {
  var isDeletionKeycode = (ev.keyCode == 8 || ev.keyCode == 46);
  // Remove field is user is trying to delete it
  if (isDeletionKeycode && this.shouldDeleteInput(ev.target.value, this.select('inputsSelector').length)) {
    $(ev.target.parentNode).remove();
  }
  // Add another field dynamically
  if (this.select('lastInputsSelector')[0] && (ev.target == this.select('lastInputSelector')[0]) && !isDeletionKeycode) {
    this.select('inputsContainer').append(InputTemplate());
  }
  // Render fields
  that.trigger('uiUpdateInputs', {
    inputs: that.collectInputs()
  });
}

And finally triggers uiUpdateInputs:

this.after('initialize', function() {
  this.on(document, 'uiUpdateInputs', this.updateInputs)
});

this.updateInputs = function(ev, data) {
  // Render all inputs provided by user
  this.select('inputListSelector').html(InputsTemplate({ inputs: data.inputs }));
}

All of this functionality works as expected on Chrome and Firefox. Users can type into the input and see the page change in 'real time'. Users also get additional fields that they can enter text into and see the page change.

The issue in question arises when using Safari, as a user enters text into the described input field the text in the input field becomes highlighted (selected) and when they enter the next character all the content is replaced with that single character. This results in the user not being able to enter more than 1 or 2 characters before having them all replaced by the next entered character.

I have tried several approaches to fix this problem but none have worked, they include:

I am very confused why this is happening and I am wondering if this is a bug in webkit with Flight. I see no issue with the Firefox or Chrome versions of this page. Thanks for any help!


Solution

  • This seems to be an issue with certain versions of Safari. When listening for the keyup function in javascript it will automatically select all of the text in the box and subsequently delete it all when the next key is typed. To prevent this from happening call preventDefault on the event object that is passed to the keyup function.

    this.on('keyup', function(e) {
      e.preventDefault()
    });