0

I wrote this code. Which sends input values to the API after pressing enter. I tried to use array, but the code causes duplicates. But duplicates aren't the only problem. Some values are not added to the array. Always 1 value after the first press of enter. Dropping values and duplicates occur regardless of API status.

<input type="text" name="qr"  class="search form-control"/>

$(document).ready(function() {
    var exist_qrs = new Set();
    // I try use array but code duplicate elements
    $("input").on("keydown", function search(e) {
        if (e.keyCode == 13) {
            input_qr = $(this).val();
            $.ajax({
                url: "API URL",
                type: "POST",
                dataType: 'json',
                data: {
                    qr: input_qr
                },
                success: function(response) {
                    if (response[8] == 1) {
                        // response[8] - status from api
                        exist_qrs.add(input_qr);
                        console.log(exist_qrs)
                    }
                }
            })
            $(this).val('')
        }
    });
});
bobi
  • 61
  • 6
  • 1
    Your second log of `exist_qrs` happens before the ajax call is complete. – Heretic Monkey Feb 15 '21 at 15:53
  • Or, to copy other people's analogy: you're trying to eat your pizza before it's been delivered – freedomn-m Feb 15 '21 at 16:21
  • @HereticMonkey ok, but that doesn't explain why the code is missing push :( How do I use push in this code to avoid my problems? – bobi Feb 15 '21 at 17:55
  • `add` is the `Set` equivalent of `Array`'s `push`. Eventually, `exist_qrs` will contain the data, but it depends on Enter having been pressed in an input, the API call returning, and the ninth element of the array in the response equaling 1. You shouldn't be getting duplicate values with `Set`. Dropped values could occur if the user types a value and presses Enter before the API response has come back. – Heretic Monkey Feb 15 '21 at 18:46

0 Answers0