Carl Jan Binalla Carl Jan Binalla - 2 months ago 9
Javascript Question

How to send a <select> in a form using the enter key without a submit button

As the title states, Is it possible? Or do I really need a submit button to submit it?

I tried something but unfortunately it didn't work for me, or maybe there's an error in the code.

Here is the code that I've tried:

document.getElementById("select_id").addEventListener('keypress', function(event) {
if(event.keyCode == 13) {
document.getElementById("form_id").submit();
};
});


Here's the html:

<form id="form_id" action="processor.php" method="POST">
<select id="select_id" name="chosenProduct">
<option value="product_a">Product A</option>
<option value="product_b">Product B</option>
</select>
</form>

Answer

hello try something this

add event.preventDefault(); before document.getElementById("form_id").submit();I think you missed this.
IF still doesn't work then

use below codes using keypress function

  /* without button*/

  $(document).ready(function(){
  $("#select_id").keypress(function(event) {
  if (event.which == 13) {
  event.preventDefault();
  $("#form_id").submit();
  }
  });
 });

/* with button key press event*/

  $("#select_id").keyup(function(event){
  if(event.keyCode == 13){
    $("#id_of_button").click();
   }
   });

Hope this helps you.

Comments