0

I'm trying to do a little script that allows a user to automatically creates a div once the tab button is pressed and the focus is on the y input.

That div is a duplicated of the previous div.

I don't know what I'm missing, but it only triggers with the first element, and not the dinamically created ones.

This is my code:

<script type="text/javascript">
        $(document).ready(function() {
            createElement();
            $('.y').on('keydown', function(event) {
                if (event.repeat) {
                    return;
                }
                if(event.key === "Tab") {
                    createElement();
                }
                $(this).unbind('keydown');
            });
        });
        function createElement() {
            $('body').append('<div class="clue-div"><div class="clue-name"><label>Pista:</label><select id="clue-name"></select></div><div class="clue-coords"><label>X:</label><input type="number" class="x"><label>Y:</label><input type="number" class="y"></div></div>');
            $.get('/get_element_names.php', function(data) {
                $.each(data, function(index, val) {
                    $("select:last").append('<option value="'+val.name+'">'+val.name+'</option>');
                });
            });
        }
    </script>

Can you guys help me with this? Thank you in advance.

  • 1
    `$(document).on('keydown', '.y', function(event) {...` – Rory McCrossan Apr 01 '22 at 16:28
  • I would also suggest that you put the HTML directly in to the page when the page loads (not making an AJAX request to get the `select` content on page load), and also `clone()` the existing HTML and append it to create the new code block. This will also avoid having to make another AJAX request to fill the select with content you already have. Also note that you're going to be creating multiple `#clue-name` elements as the new content gets created, which is invalid - change that to a class. – Rory McCrossan Apr 01 '22 at 16:34
  • 1
    Solved, thank you @RoryMcCrossan. Also thank you for the recomendation, I'll keep that in mind and change it. THX – David Encina Martínez Apr 01 '22 at 18:32

0 Answers0