Reputation: 65
I want to send multiple data from on click function to jquery function like this code.
When I click on my button I get [object Object]undefined]
in alert box
Code :
$(function() {
$("#button").click(function myf(data1, data2) {
alert(data1 + data2);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="button" onclick="myf('hello','word');">click</a>
How can I do it?
Upvotes: 1
Views: 6367
Reputation: 454
As said you have already a listener, I don't see the point of adding an other one.
<button onclick="myf('hello','word')">click</button>
<script>
function myf(data1,data2){
alert(data1+data2);
}
</script>
https://jsfiddle.net/wnd6ovkf/
And the jquery version:
<button data1= "value" data2= "value2" class="btn">click</button>
<button data1= "ohtervalue" data2= "othervalue2" class="btn">click</button>
<script>
$(".btn").click(function() {
alert(this.getAttribute("data1") + " " + this.getAttribute("data2"));
});
</script>
https://jsfiddle.net/wnd6ovkf/6/
Upvotes: 0
Reputation: 823
You are using 2 event that will both try to listen to the onclick event you can remove one of them like so :
<script>
$(function() {
$("#button").click(function() {
alert('hello' + 'word');
});
});
</script>
An id is always unique so you can put your value directly into the function.
if you really want to use jquery you can use this:
$("#button").click(function() {
var data = $(this).data('params').split('|');
alert(data[0] + data[1]);
});
And this for the html :
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a href="#" id="button" data-params='hello|world'>click</a>
Upvotes: 2
Reputation: 118
Following code should do the trick:
function myf(data1, data2) {
alert(data1 + data2);
return false;
}
<a id="button" href="#" onclick="myf('hello', 'word');">click me</a>
return false; is to prevent default action.
Upvotes: 1
Reputation: 72857
There's absolutely no point in passing the data from HTML.
You're binding that function to the button's id
. That id
must be unique, so there's only ever that single combination of values.
Just use this:
$(function() {
$("#button").click(function() {
alert('hello' + 'word');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="button">click</a>
Or, if you want to send the data from the HTML, you're going to have to do something like this:
function mf (data1, data2){
alert(data1 + data2);
}
<a href="#" id="button" onclick="mf('hello','word');">click</a>
Or, if you want to use jQuery, you're going to have to do something convoluted like this:
$("#button").click(function() {
var data = $(this).data('params').split(',');
alert(data[0] + data[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="button" data-params='hello,word'>click</a>
Upvotes: 3