0

I have a simple question. My JS code is like this, but when I try to add a new element or content to the <div>, it comes up then goes up quickly. I don't know why.

How can I avoid this?

 <head> $(document).ready(function () { $('#mybtn').click(function () { $('#main').append('<button id ="mm" onclick="myfun()">generate code my fun.</button>'); }); }); </head> <body> <form id="form1" runat="server"> <button id ="mybtn">generate code</button> <div id="main"></div> </form> </body> 
9
  • It seems to be working fine: http://jsfiddle.net/xCB4a/ Commented Nov 14, 2013 at 11:52
  • 1
    You could try setting the button type, example : <button type="button" id="mybtn">generate code</button>. This will stop the button from Submitting. Commented Nov 14, 2013 at 11:53
  • I ma including js code like this. <script src="code.jquery.com/jquery-1.9.1.js"></script> that cause to problem?? Commented Nov 14, 2013 at 11:53
  • 1
    Is your content wrapped inside a <form> tag? (If its .ASPX then I guess it would be.) If so then try my suggestion of setting the type of the button. Commented Nov 14, 2013 at 11:55
  • 1
    so you did not include all of your code ... Commented Nov 14, 2013 at 11:56

3 Answers 3

1

You should stop the button from Submitting the form by setting the button's type to be that of button.

Example :

<button type="button" id="mybtn">generate code</button> 

The default type for a <button> element is submit. Which is causing your <FORM> tag to submit.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$('#mybtn').click(function (e) { e.preventDefault(); $('#main').append('<button id ="mm" onclick="myfun()"> generate code my fun </button>'); return false; }); 

1 Comment

but why this happen ,it is just a simple aspx page??there other some sample s on the net and works fine!
0

Try with:

$('#mybtn').click(function (event) { event.preventDefault(); $('#main').append('<button id ="mm" onclick="myfun()"> generate code my fun </button>'); }); 

preventDefault : If this method is called, the default action of the event will not be triggered.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.