0

I want to do some actions when a button on my page is clicked, but my function executes without clicking on the button and when I check the log using firebug I got "undefine" message. Below is my code snippet so far.

var email = example@example.com   
"<button class='btn btn-warning' onclick ='"+addNote(email)+"' >Add Note</button>"

function addNote(youremail){
     alert("Your email is "+ youremail);
}

With the above code snippet the output will be Your email is example@example.com.

fanbondi
  • 1,035
  • 5
  • 18
  • 37
  • 1
    See this post: http://stackoverflow.com/questions/9643311/pass-string-parameter-in-an-onclick-function. Your code is actually calling the function addNote, not inserting it into the HTML. – maxedison Jan 21 '14 at 23:20

1 Answers1

3

That is because you are calling the function instead of adding it into your string.

"<button class='btn btn-warning' onclick ='addNote(email)' >Add Note</button>"

See this example:

http://jsfiddle.net/sP35v/

Timeout
  • 7,759
  • 26
  • 38
  • will this not treat the parameter as a regular string instead of a variable? – fanbondi Jan 21 '14 at 23:31
  • @fanbondi No, it will treat it as a variable. If email were a string your event would look like this: onclick="addNote('email')" -> See the difference? – Timeout Jan 21 '14 at 23:33
  • Oh okay I got it,however in the console it says email is not define even-though I defined it before calling it. – fanbondi Jan 21 '14 at 23:38
  • @fanbondi Did you quote that example email address? Please see the jsfiddle link I included in my post. It will show a working version. – Timeout Jan 21 '14 at 23:40