Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  134] [ 2]  / answers: 1 / hits: 61583  / 10 Years ago, thu, june 19, 2014, 12:00:00

I am new to Javascript. I want to write a javascript code that when I click a button, the alert window pops up and writes data-message attribute. Here is my code:



<button type=button data-message=a1 onclick=pop()>click</button>

<script>
function pop() {
alert(this.getAttribute(data-message));
}
</script>


but I get the error



TypeError: this.getAttribute is not a function
alert(this.getAttribute(data-message));


I have two questions:




  1. What is wrong?


  2. How can I debug this? How can I find out what this refers to? I am using firebug.




Thanks a lot.


More From » javascript

 Answers
14

You need send this on the button like



<button type=button data-message=a1 onclick=pop(this)>click</button>


and the Js, capture who is calling it.



function pop(e) {
alert(e.getAttribute(data-message));
}


Working DEMO


[#70515] Monday, June 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
jonrened questions
Mon, Nov 2, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
Tue, Jan 21, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
;