Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Without clicking the button its click event executing javascript

I have a HTML form which contains a input text and a button. HTML

<form id="form1">
   <input type="text" />
   <button onclick='YouClick();'>Click</button>
 </form>

JS function

 function YouClick() {
   alert("You just clicked");
 }

When user click the button , the javascript function YouClick executes. But if i pressed enter key on input text fields than also YouClick function executes. How can i stop this behaviour ? So that only by clicking the button the YouClick function executes.

like image 707
user1740381 Avatar asked Oct 31 '12 10:10

user1740381


People also ask

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.

What is alternative for onclick?

event: Event can be any valid JavaScript event. Events are used without the “on” prefix like use “click” instead of “onclick” or “mousedown” instead of “onmousedown”. listener(handler function): It can be a JavaScript function that responds to the event that occurs.

How do you trigger a button click event?

A single click event bind to a button with an Id of “button2”. and a trigger to execute the button1 click event handler. $("#button2"). bind("click", (function () { alert("Button 2 is clicked!"); $("#button1").

Can you use onclick without JavaScript?

Most people will tell you that it is not possible, however that is simply not true. The only way to submit data without JavaSript , is by using submit buttons. The submit buttons can be styled similar to text but it's not ideal. Simply make the submit buttons hidden and use labels with a corresponding for attribute.


2 Answers

You are submitting the form, then the button which by default is type='submit' is triggered, you can set the type attribute of the button as button:

<button type='button' onclick='YouClick();'>Click</button>
like image 84
undefined Avatar answered Oct 09 '22 11:10

undefined


This should work :

$(document).ready(function() {
  $('input').keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
    }
  });
});
like image 4
Pranav 웃 Avatar answered Oct 09 '22 12:10

Pranav 웃