1 year ago

#364588

test-img

David Encina Martínez

Can't trigger event more than once (Jquery, HTML)

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.

javascript

html

jquery

tabs

keydown

0 Answers

Your Answer

Accepted video resources