jQuery .trigger() method has changed the way custom events will be created, handled and later executed. Not just click but all events that are bound with an element, can be triggered using this method.
We can put it in this way. The user is asked to fill a few textboxes with data and once filled a button will be clicked to submit the contents of the webpage.
Instead of clicking the button, the user hits the enter key immediately after typing some value in the textbox, and that too triggers an event and submits the contents.
There were two events at work, not simultaneously but in a row. Since the cursor was still inside the textbox, the first event reported is the keypress event of the textbox which actually triggers the “click” event of the button, meant for submitting the data or the content.
<html> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> Enter your name <input type="text" id="tb" /> <input type="button" id="btContinue" value="Submit" /> </body> <script> $(document).ready(function() { $('input').keypress(function(event) { if (event.keyCode == 13) $('#btContinue').trigger('click'); }); $('#btContinue').click(function() { alert('Hi, ' + $('input').val()); }); }); </script> </html>
In the above example, we are first checking if the key pressed inside the textbox is the enter key, for which the keycode is 13. Now the keycode is captured using the keypress event of the input box which is also a textbox.
Note that we have 2 input boxes, a textbox and a button. We can do this more specifically by identifying the elements with its ID. This is important since a web page can have multiple textboxes each with events and out of many controls only one should trigger the click event of the button.
<body> Company <input type="text" id="tbCompany" /><br /> Enter your name <input type="text" id="tbName" /> <input type="button" id="btContinue" value="Submit" /> </body> <script> $(document).ready(function() { $('#tbName').keypress(function(event) { if (event.keyCode == 13) $('#btContinue').trigger('click'); }); $('#btContinue').click(function() { alert('Hi, ' + $('#tbName').val()); }); }); </script>
See this Demo
Press the Enter Key after entering your name. This will trigger the Submit button.