tags:

views:

56

answers:

3

Hi

I'm trying to use javascript and jquery to do some plotting, here is the code that I define the button, but the first time I click it doesn't work, the second time it works well, I don't understand why.

$('<p><input type="button" value="Plot Data" /></p>').click(getData).appendTo('#plot');

Could someone help to explain it? Thanks!

Mengfei

A: 

Because the click action is on 'p'. Jquery will return the object of the outer html, in your case 'p'. Try this instead:

$('#plot').append($('<p></p>').append($('<input type="button" value="Plot Data" />').wrap('').click(getData)));
Dan
`$('<input type="button" value="Plot Data" />').click(getData).wrap('<p />').parent().appendTo('#plot');` :)
Nick Craver
Hi Dan,with your code I didn't get the button...
Mengfei
Hi Nick, with your code it still needs twice click..
Mengfei
A: 

Have you tried removing the "p" tags from your code?

Jason
Hi, I just tried and the first click still doesn't work
Mengfei
+1  A: 
var 
  // function for event click
  getData = function(ev) {
      alert('ok');
  },
  // your button
  button = $('<input type="button" value="Plot Data" />').click(getData),
  // append to p container
  pcontainer = $('<p></p>').append(button).appendTo('#plot');

example

EDIT for comments

var 
  // counter clicks
  clickCounter = 0,
  // function for event click
  getData = function(ev) {

      $('#controlClick').append('click in getData '+(++clickCounter)+'<br />'); // firsts lines

      // your code;
      // don't put return false or ev.stopPropagation()
  },
  controlEvent = function(ev) {
      $('#controlClick').append('click in control<br />');
  },
  // your button
  button = $('<input type="button" value="Plot Data" />')
    .bind('click', getData)
    .bind('click', controlEvent),
  // append to p container
  pcontainer = $('<p></p>').append(button).appendTo('#plot');​

example update

andres descalzo
Hi Andres, thank you for the example, I changed with your code, but it still needs twice click, maybe there's something wrong with my getData function...really confused now.
Mengfei
try this simple event handling
andres descalzo