Nesiehr
Nesiehr

Reputation: 247

Replacing input text when tab is pressed ( Chrome Extension )

So basically what I'm trying to do is identify if the input bar has "y" typed in it and when tab key is pressed replace that y with "youtube ".

Javascript

var input = document.getElementById('searchbar').value;
var words = input.split(" ");

$("#searchbar").keydown(function(e) {
if(e.keyCode == 9) {
    e.preventDefault();
    if(input == 'y') {
        $('#searchbar').text('youtube');
    }
}
});

Currently I'm not getting any error messages, its just not working. The tab key also moves the focus away from the input bar.

Upvotes: 0

Views: 126

Answers (1)

Aman Virk
Aman Virk

Reputation: 3977

Here is why

  1. You should be getting value on keydown , not on page load as at the time of loading page value is empty.
  2. As you are using jquery , get current value of input using jquery facade/selector
  3. Finally you update the input box value not text

Try this

    $("#searchbar").keydown(function(e) {
      var input = $('#searchbar').val();
      var words = input.split(" ");

     if(e.keyCode == 9) {
      if(input == 'y') {
        $('#searchbar').val('youtube');
      }
      e.preventDefault();
    }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter Search Term
<input type="text" id="searchbar">

Upvotes: 2

Related Questions