1

Check the code bellow. When i enter some keyword in input field and press Search button its successfully redirecting to youtube url but if i press enter then this not redirecting however i used .click() method for enter press. How can i fix it? I want redirection on press enter key from keyboard and also press search button. How can i fix it?

$(document).ready(function () {
  $(document).on("keypress", function(e){
      $("#srcBtn").click();
  });

  $('#srcBtn').on('click', function () {
      var srcValue = $('#srcValue').val();
      var youtubeUrl = 'https://www.youtube.com/results?search_query=';
      //console.log(srcValue);
      window.open(youtubeUrl+srcValue,"_self");
  });    
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
<div class="container">
  <form method="get" action="">
    <br/>
    <br/>
    <br/>
    <div style="text-align:center;">
      <input type="text" class="form-group form-control input-lg" id="srcValue" value="" placeholder="Search YouTube">
      <button type="button" class="btn btn-info btn-lg" id="srcBtn">Search</button>
    </div>
  </form>
</div>    
    

   
John Doe
  • 317
  • 1
  • 3
  • 8
  • 3
    Possible duplicate of [How to detect pressing Enter on keyboard using jQuery?](https://stackoverflow.com/questions/979662/how-to-detect-pressing-enter-on-keyboard-using-jquery) – Calvin Nunes Oct 02 '18 at 13:27

2 Answers2

0

instead of calling just click please use trigger("click")

$(document).ready(function () {

 $(document).on("keypress", function(e){
if(e.key ==  'Enter') {
   $("#srcBtn").trigger("click");
}

        });


        $('#srcBtn').on('click', function () {
            var srcValue = $('#srcValue').val();
            var youtubeUrl = 'https://www.youtube.com/results?search_query=';
            //console.log(srcValue);
            window.open(youtubeUrl+srcValue,"_self");
        });

        });
Shyam Kumar
  • 148
  • 9
0

I would prefer doing the search part in a function and triggering that. And not some weird "button per code clicking". Buttons are for humans to trigger code and not the other way around ^^

$(document).ready(function () {
  $(document).on("keypress", e => {if(e.key == "Enter") searchYoutube()});
  $('#srcBtn').on('click', searchYoutube);
  function searchYoutube() {
    var srcValue = $('#srcValue').val();
    var youtubeUrl = 'https://www.youtube.com/results?search_query=';
    //console.log(srcValue);
   window.open(youtubeUrl+srcValue,"_self");
  }
});
Elias
  • 3,592
  • 2
  • 19
  • 42