Reputation: 1981
Ok, i am looping through a JSON dataset and populating a div, using Jquery templates. For each loop, i create a button, with a value.
Now, i hook up the click event to a function within the loop using this:
<button id="btnAddGoodGuy" class="btn btn-success btn-xs" type="button" data-toggle="tooltip" data-original-title="Good guy?" onclick=" addGoodGuy(event); " value="${MatchedString}"><i class="fa fa-user-md"></i></button>
my problem, is the value of the button within the function addGoodGuy is always the first value. So in my loop if had three button with value a value b and value c respectively, i'd always end up with value a, irrespective of which button i clicked.
So far, my addGoodGuy function looks like this:
function addGoodGuy(event) {
event.preventDefault();
$('[data-toggle="tooltip"]').tooltip();
var matchedItem = $('#btnAddGoodGuy').val();
alert("The value is " + matchedItem);
}
How can I get at the individual button values within my function?
Upvotes: 1
Views: 161
Reputation: 2986
you can't use the same id="btnAddGoodGuy"
for different buttons. try this way:
<button class="btn btn-success btn-xs" type="button" data-toggle="tooltip" data-original-title="Good guy?" onclick=" addGoodGuy(event, this); " value="${MatchedString}"><i class="fa fa-user-md"></i></button>
and the function
function addGoodGuy(event, element) {
event.preventDefault();
$('[data-toggle="tooltip"]').tooltip();
var matchedItem = element.value;
alert("The value is " + matchedItem);
}
Upvotes: 1
Reputation: 195992
First of all you need to make your id
s to be unique (otherwise it is invalid html)
Then you should avoid using event attributes (inline scripts) and bind the handler through jQuery.
<button id="btnAddGoodGuy" class="btn btn-success btn-xs" type="button" data-toggle="tooltip" data-original-title="Good guy?" value="${MatchedString}"><i class="fa fa-user-md"></i></button>
And bind the handler to the container div
(the one you are populating)
$('containerDivId').on('click', 'button.btn', function(e){
e.preventDefault();
var value = this.value;
alert("The value is " + value);
});
Upvotes: 1