Anusha
Anusha

Reputation: 31

Trigger a button click with jQuery when enter button click

This is jQuery code of mine.instead of using proceed button when i click on enter remaining text boxes should display

$("#btnValidateMember").click(function () {
  if ($("#txtUserEmail").val() == "") {
    $("#txtUserEmail").addClass("error");
    //$("#spnUserEmail").text("required");
  }
  else if($("#spnUserEmail").text() == "")
  {
    GetMemberDetailsbasedonEmailId($("#txtUserEmail").val());
  }
  $("#ddlBusinessState").empty().append($("<option/>"));
  //$("#ddlBusinessCity").empty().append($("<option/>"));
  $("#ddlBusinessState").select2({ placeholder: 'State', allowClear: false });
  //$("#ddlBusinessCity").select2({ placeholder: 'City', allowClear: false, width: '366px' });
  BindStatesBasedOnCountryId("1",`enter code here` "ddlBusinessState", "");enter code here

});

Upvotes: 1

Views: 107

Answers (2)

Justin Liu
Justin Liu

Reputation: 631

$("#textbox").on('keydown', function(e) {
  const ENTER_KEY_CODE = 13;
  const ENTER_KEY = "Enter"
  var keycode = e.keyCode || e.which;
  var key = e.key;
  if (keycode == ENTER_KEY_CODE || key == ENTER_KEY) {
    document.querySelector("#BtnValidateMember").click();
  }
});
.button {
  padding: 15px 25px;
  font-size: 24px;
  text-align: center;
  cursor: pointer;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

.button:hover {
  background-color: #3e8e41
}

.button:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

#textbox {
  border-radius: 15px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="BtnValidateMember" class="button" onclick="alert('Button Pressed')">Button</button>
<input type="search" id="textbox">

Upvotes: 1

Sahil Patel
Sahil Patel

Reputation: 1620

Please see this jsbin

$(document).keypress(function(e) {
    if(e.which == 13) {
        $('#btnValidateMember').trigger('click');
    }
});

Above jQuery code will detect the keypress event If you have pressed enter button it will trigger the click event of #btnValidateMember button.

Upvotes: 0

Related Questions