Search code examples
phphtmljqueryvalidationenter

Handle multiple operations inside a single jQuery method when we press Enterkey from a textbox


I want to handle two operations when I click the enter key after entering text in one textbox. Two operations are

  1. Move the cursor to the next textbox
  2. Establish a serial communication using php code

$(function() {
  $('input:text:first').focus();
  var $inp = $('input:text');
  $inp.bind('keydown', function(e) {
    //var key = (e.keyCode ? e.keyCode : e.charCode);
    var key = e.which;
    if (key == 13) { // Enter key is pressed
      e.preventDefault(); // Prevent the default behaviour of enter key
      var nxtIdx = $inp.index(this) + 1;
      $(":input:text:eq(" + nxtIdx + ")").focus();
      // Ajax query to send request to php
      var test = $("#command-text").val();
      var inputtext = test;
      var command = "1";
      // var mode = $(".common-input mb-20").val();
      $.ajax({
        type: "POST",
        url: "controller.php",
        data: {
          inputtext: inputtext,
          command: command
        },
        cache: false,
        success: function(html) {
          var feedback = "@" + $("#command-text").val() + "#";
          $("#feedback").val(feedback);
        }
      });
    }
  });
});

When I tried out with the following code,only one operation is executing,either cursor will move to the next textbox or establish communication. Kindly help me to solve this issue Code I tried is as below


Solution

  • You are using incorrect syntax your position of brackets is not correct try this:

    $(function() {
      $('input:text:first').focus();
      var $inp = $('input:text');
      $inp.bind('keydown', function(e) {
        //var key = (e.keyCode ? e.keyCode : e.charCode);
        var key = e.which;
        if (key == 13) { // Enter key is pressed
          e.preventDefault(); // Prevent the default behaviour of enter key
          var nxtIdx = $inp.index(this) + 1;
          $(":input:text:eq(" + nxtIdx + ")").focus();
          // Ajax query to send request to php
          var test = $("#command-text").val();
          var inputtext = test;
          var command = "1";
          // var mode = $(".common-input mb-20").val();
          $.ajax({
            type: "POST",
            url: "controller.php",
            data: {
              inputtext: inputtext,
              command: command
            },
            cache: false,
            success: function(html) {
              var feedback = "@" + $("#command-text").val() + "#";
              $("#feedback").val(feedback);
            }
          });
        }
      });
    });