Reputation: 618
I am new to javascript so sorry if this isn't technical.
I have an html
<button type="button" id="btnlocation" value="chicken">Click me</button>
So i am trying to pass the string value "chicken" into the button click function
$('#btnlocation').click(function (value) {
alert(value); // This should output chicken
}
But instead it outputs [Object],[Object] so how do i get the value or convert it into string?
thank you
Upvotes: 2
Views: 2104
Reputation: 6311
for getting the value use $(this).val() for getting the id of the button use $(this).attr("id")
$('#btnlocation').click(function () {
alert($(this).val()); // this is used get the value
alert( $(this).attr("id")); // this is used to get the id of the button
});
Upvotes: 0
Reputation: 7042
It is ideal to pass the event it self to the on event method. From that event you can get whatever value you want of that element.
You can change you JavaScript as below to do so:
$('#btnlocation').click(function (e) {
alert(e.target.value); // This should output chicken
});
Upvotes: 0
Reputation: 1
try this
$(document).ready(function(){
$('#btnlocation').click(function(){
alert($('#btnlocation').val());
});
});
Upvotes: 0
Reputation: 115222
The first argument in callback refers to event
object. For getting the value either use this.value
or $(thid).val()
where this
refers to the dom object of clicked element.
$('#btnlocation').click(function () {
alert(this.value);
// or
alert($(this).val());
})
$('#btnlocation').click(function() {
console.log(this.value);
// or
console.log($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="btnlocation" value="chicken">Click me</button>
Upvotes: 4
Reputation: 1643
you should use this
$('#btnlocation').click(function () {
alert($(this).val()); // This should output chicken
});
Upvotes: 1