Reputation: 13
I'm using javascript to insert buttons dynamically into a document, and I want to have the buttons clickable and grab the value of each button and export them in the conosle.log. Right now I have the button clickable, but I can't figure out how to pass the button value from the .on() to the function, any advice?
html
<button id="testTagButton" class="yt-chip" title="test button please ignore"><span>test button please ignore</span></button>
javascript
$(document).on('click','#testTagButton',tagInsert);
function tagInsert(){
console.log("Button Value should go here");
}
I have to use .on() afaik because I'm using append to insert the button into the document
Upvotes: 1
Views: 53
Reputation: 110
Not sure which value you were looking for, but $(this).id or $(this).text would do it
Upvotes: 1
Reputation: 2835
You can use the data-
and the $.data()
.
$(document).ready(function() {
$("#test").on("click", function(e) {
console.log($(this).data("test"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-test="123" id="test">
Test
</button>
Upvotes: 0
Reputation: 138267
Simply refer to the context (aka this):
function tagInsert(){
console.log(
this.id, //a regular DOM prop
this.title,
$(this).text() //or utilizing jquery again
//or whatever
);
}
Upvotes: 3