jquery - Without clicking the button its click event executing javascript - Stack Overflow

I have a HTML form which contains a input text and a button.HTML<form id="form1"><i

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.

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.

Share Improve this question edited Oct 31, 2012 at 10:25 Neji 6,8595 gold badges45 silver badges66 bronze badges asked Oct 31, 2012 at 10:20 user1740381user1740381 2,1979 gold badges40 silver badges62 bronze badges 2
  • 1 Your button is inside the form. So when you are pressing the enter button its being pressed. Put it outside the form and see. Its not a solution. Solutions are given below. I am just telling you the reason – polin Commented Oct 31, 2012 at 10:26
  • @NejiHyuga: why would you need a fiddle for that? – Michal B. Commented Oct 31, 2012 at 10:31
Add a ment  | 

2 Answers 2

Reset to default 4

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>

This should work :

$(document).ready(function() {
  $('input').keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
    }
  });
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745171382a4614946.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信