2

I would like, that when the Enter button is pressed, the application will search a city, the action now is started by pressing the Search button. Below is my code:

const ENTER_KEY_CODE = 13;
document.querySelector('#city').addEventListener('keyup', function(e) {
  if (e.keyCode === ENTER_KEY_CODE) {

        var city = $(this).val();
        if (city !== '') {

            $.ajax({

                url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
                    "&APPID=bb037310921af67f24ba53f2bad48b1d",
                type: "GET",
                dataType: "json",
                success: function (data) {
                    var widget = show(data);

                    $("#show").html(widget);

                    $("#city").val(' ');
                }

            });

        } else {
            $("error").html('Field cant be empty')
        }

    };
});
Alexey
  • 49
  • 1
  • 8
  • 3
    Use the `submit` event of the form, not a keypress event on the text input or a click event on the button. – Bergi Dec 27 '18 at 17:06
  • +1 for switching to a `` inside the form, then using jQuery's `submit()` as the form submit handler. Better for accessibility and you'll get the onkeypress event too. – Toby Dec 27 '18 at 17:10
  • 1
    Possible duplicate of [Trigger a button click with JavaScript on the Enter key in a text box](https://stackoverflow.com/questions/155188/trigger-a-button-click-with-javascript-on-the-enter-key-in-a-text-box) – kvk30 Dec 27 '18 at 17:13

3 Answers3

2

All you need to do is add a keyup events listener to your input element. When the handler is called, simply check the e.keyCode to see if it's enter was pressed. If it was, do your thing:

const ENTER_KEY_CODE = 13;
document.querySelector('#textEl').addEventListener('keyup', function(e) {
  if (e.keyCode === ENTER_KEY_CODE) {
    var city = $(this).val();
    var url = `http://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&units=metric&APPID=bb037310921af67f24ba53f2bad48b1d`;
    if (city !== '') {
      console.log(`Make ajax call to ${url}`);
      //Make your AJAX call here
    } else {
      console.log('City cannot be blank!');
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="textEl" type="text" />
<div id="error"></div>
Tom O.
  • 5,730
  • 2
  • 21
  • 35
  • $(document).ready(function () { $('#submitWeather').addEventListener('keyup',function (e) { if (e.keyCode ===13){ var city = $("#city").val(); if (city !== '') { $.ajax({ – Alexey Dec 27 '18 at 18:04
  • I an add this code, but it doesn't work. What's wrong? – Alexey Dec 27 '18 at 18:05
  • I updated the code. I think this should help you out. Let me know. – Tom O. Dec 27 '18 at 18:14
  • I have this error "Uncaught TypeError: Cannot read property 'addEventListener'" – Alexey Dec 27 '18 at 18:21
  • Can you post your HTML too? – Tom O. Dec 27 '18 at 18:22
  • The problem was in HTML...now I add – Alexey Dec 27 '18 at 18:40
  • But now button "Search" doesn't work, can I make any changes, that be available two ways to search (by click of mouse and click Enter button? – Alexey Dec 27 '18 at 18:54
  • If the code isn't working I can take a look, if you post all the relevant HTML too. – Tom O. Dec 27 '18 at 19:00
  • And what about this? But now button "Search" doesn't work, can I make any changes, that be available two ways to search (by click of mouse and click Enter button? – – Alexey Dec 27 '18 at 19:29
  • Yes, you can definitely make the search available 2 ways. Just add a click listener to the "Search" button via `addEventListener('click', someFunc)` where `someFunc` is your search function. Let me know if that doesnt make sense to you. – Tom O. Dec 27 '18 at 21:06
  • It doesnt make sense for me( Can you please change the code with this function – Alexey Dec 27 '18 at 21:47
0

This a sample code please use this a reference code.

HTML code

<input id="InputEnter" >

Javascript code

var input = document.getElementById("InputEnter");
input.addEventListener("keyup", function(event) {
  event.preventDefault();
  if (event.keyCode === 13) {
   $(document).ready(function () {

$('#submitWeather').click(function () {

    var city = $("#city").val();
    if (city !== '') {

        $.ajax({

            url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
                "&APPID=bb037310921af67f24ba53f2bad48b1d",
            type: "GET",
            dataType: "json",
            success: function (data) {
                var widget = show(data);

                $("#show").html(widget);

                $("#city").val(' ');
            }
  }
});
kvk30
  • 1,133
  • 1
  • 13
  • 33
0

This should work. I assume that your ajax request is correct.

document.querySelector('#submitWeather').addEventListener('keypress', function(e){
        if(e.which === 13){
            // your ajax request
        }
    })
Marios Simou
  • 181
  • 3
  • 8