How can I submit with button and Enter in Jquery? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can I submit with button and Enter in Jquery?

Which is the best way to add a keypress function to call a click function? If there is a better way to get this done please let me know as I ma new to jquery. Here's my current code: $(function(){ $("#add").click(function() { var val = $("input").val(); if (val !== ''){ var elem = $("<li></li>").text(val); $(elem).append("<button class='rem'>X</button>"); $("#myList").append(elem); $("input").val(""); $(".rem").on("click", function(){ $(this).parent().remove(); }); } }); $('#add').keypress(function(e){ if(e.which == 13){ $('#add').click(); } }); });

17th Nov 2018, 2:04 PM
Jo$3
Jo$3 - avatar
3 Answers
+ 11
Remove the $ and use the dot to join the two ....eg. $("div").click(function (e){ alert ("event"); }).keydown(function (e){ alert ("event"); });
17th Nov 2018, 3:14 PM
Barak
Barak - avatar
+ 11
Assign the button with an id and select it with jquery Like in $("#buttonId").click(function(e){})
17th Nov 2018, 6:15 PM
Barak
Barak - avatar
+ 1
Not working because on my HTML code the events are triggered from the button and not input box. I will work on changing that and will try again. Will share the update once I get it working thanks @Barak
17th Nov 2018, 3:47 PM
Jo$3
Jo$3 - avatar