简体   繁体   中英

How do I create a new input on tab with jQuery (or vanilla JS)

Like many things, my question is best explained with a picture: http://gyazo.com/f7df971c91a5ab4a4969d12f4c5f32b6.png?1329575807

When the user is on the last field in each column, I want a new input to pop up underneath the current input when they press tab (similar to what Quizlet does).

I don't have that much experience with jQuery, could someone help me out, or point me in the right direction?

EDIT: So here's what I have currently:

$(document).ready(function(){
$('section#attendance input:last').keydown(function(e) {
    if (e.which == 9)
    {
        var $this = $(this);
        var num = parseInt($this.attr('name').match(/\d+(,\d+)?/)[0]) + 1;
        $this.parent().append('<input type="text" name="attendance[' + num +']" value="Name and Position" class="medium" />');
    }
});

});

For some reason, after it creates the first new input, it doesn't use that new input for the tab trigger, but rather the input it used before. Any idea why?

$('input[type="text"]:last').live('keyup',
    function(e) {
        if (e.which == 9) {
            $(this).parent().append($('<input/>', {
                value: '',
                type: 'text',
                            name: 'YOUR_CHOICE',
                            class: 'YOUR_CHOICE'
            }));
        }
    });

Assuming you have the column fields in some contanier (eg a 'column' div) and the fields have class field , and the last field has class last , then this might help:

$('.last').live('focusout', function() {
  var $this = $(this);
  $this.removeClass('last');
  $this.parent().append('<input class="field last" type="text"></input>');
});

Of course, you could append something a lot prettier than that ;)

function KeyDown(e) {
    if (e.which == 9) { // tab
        // Do your stuff
    }
}

$(document).keydown(KeyDown);

In your case you'll probably not want to bind to document, but to the last element. Or you could do that focus check inside the handler method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM