Tabish Rizvi
Tabish Rizvi

Reputation: 367

Unable to manually trigger keydown event with jquery

<form>
    <div id="part-inputs">
        <div class="part-input">
            <label>Part 1</label>
            <input type="number" class="start" name="s[0]" value="" placeholder="start time" tabindex="3">
            <input type="number" class="finish" name="f[0]" value="" placeholder="finish time" tabindex="4">
        </div>
    </div>
    <input type="submit" name=submit>
</form>

<script>
    var nextPartNo = 2;
    var template = '<div class="part-input">' +
        '<label>Part <%= partNo %></label>' +
        '<input type="number" class="start" name="s[<%= partNo -1 %>]" value="" placeholder="start time" tabindex="<%= (partNo-1)*2+1 %>">' +
        '<input type="number" class="finish" name="f[<%= partNo -1 %>]" value="" placeholder="finish time" tabindex="<%= (partNo-1)*2+2 %>">' +
        '</div>';
    var compiledTemplate = _.template(template);

    // check for tab keydown at finish field
    $("#part-inputs").on('keydown', '.finish', function(event) {

        var keyCode = event.keyCode || event.which;

        if (keyCode == 9) { // tab key
            var $partInputTargeted = $(event.target.parentElement); // div#part-input
            if (!$partInputTargeted.is(':last-child')) {
                return;
            }
            $("#part-inputs").append(compiledTemplate({
                partNo: nextPartNo
            }));
            nextPartNo++;
        }
    });

    // check for enter key at both fields
    $("#part-inputs").on('keydown', ['.start', '.finish'], function(event) {

        var keyCode = event.keyCode || event.which;

        if (keyCode == 13) { // enter key
            console.log("here"); // this verifies we reach the block where we trigger jquery event 
            event.preventDefault();
            var e = jQuery.Event("keydown");
            e.which = e.keyCode = 9; // Create tab key event
            $(event.target).trigger(e);
        }
    });
</script>

Above is a snippet of the dynamic form, I am creating. There are multiple units of a start field and a finish field. Each unit is a div#part-input. All div#part-input divs are children of div#part-inputs.

On tab event triggered at finish field of last div#part-input, a new div#part-input will be appended. I am compiling the template using underscore.js( This working as expected)

Now I want enter key at any of the fields(start or finish) to trigger tab event on the same . This where code is not doing anything.

Upvotes: 0

Views: 939

Answers (2)

KungWaz
KungWaz

Reputation: 1956

First of all looks like there is a typo in your submit button, missing the quotes around the name prop.

Try this, it should work for what you are looking for. It will trigger if the enter key is pressed while in a finished input. I took out our template adding to it's own function so you can call it in multiple places.

function addTemplate() {
  var $partInputTargeted = $(event.target.parentElement); // div#part-input
  if (!$partInputTargeted.is(':last-child')) {
    return;
  }
  console.log('add new template');
}

$("#part-inputs .start, #part-inputs .finish").keydown(function (event) {
  if (event.which === 13) {
    event.preventDefault();
    
    var index = $('input').index(this) + 1;
    $('input').eq(index).focus();
    
    if($(this).attr('class') === 'finish') {
      addTemplate();
    }
  }
});

// check for tab keydown at finish field
$("#part-inputs").on('keydown', '.finish', function(event) {
  var keyCode = event.keyCode || event.which;

  if (keyCode == 9) { // tab key
    addTemplate();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <div id="part-inputs">
        <div class="part-input">
            <label>Part 1</label>
            <input type="number" class="start" name="s[0]" value="" placeholder="start time" tabindex="3">
            <input type="number" class="finish" name="f[0]" value="" placeholder="finish time" tabindex="4">
        </div>
    </div>
    <input type="submit" name="submit" />
</form>

Upvotes: 1

Michal
Michal

Reputation: 5220

If I understand it correctly you want to change focus on next input when user presses enter key. Why don't you directly set the focus with javascript? There is no need to fake keyboard events.

This snippet should help you:

$('input,select').keydown( function(e) { // Add event listener
  var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
  if(key == 13) { // If enter key
    e.preventDefault();
    var inputs = {YOUR INPUTS} // $('.YOUR-SEELCTOR-CLASS').find(':input:visible');
    var nextinput = 0;

    // Find next input
    if (inputs.index(this) < (inputs.length-1)) {
      nextinput = inputs.index(this)+1;
    }

    // Handle input focus
    if (inputs.length==1) {
      $(this).blur().focus();
    } else {
      inputs.eq(nextinput).focus();
    }
  }
});

Upvotes: 1

Related Questions