1
for (var i=0; i<data.length; i++){
    $("#menu").append("<button onclick='select_food("+data[i]['id']+","+data[i]['name']+")'>Select</button>)")
}
function select_food(id, name){
     //do something
}

There is a syntax error on this code. How can I pass two parameters for each button invoking select_food function?
Thanks.

3 Answers 3

3

Using onclick attributes is an outdated (and ugly) way of attaching events. Try using data attributes to store the information you need and attach the event with jQuery. Something like this:

$('#menu').on('click', 'button', function() {
    var id = $(this).data('id');
    var name = $(this).data('name');

    // do something...
});

for (var i = 0; i < data.length; i++){
    $("#menu").append('<button data-id="' + data[i]['id'] + '" data-name="' + data[i]['name'] + '">Select</button>')
}
Sign up to request clarification or add additional context in comments.

Comments

1

Since the parameter name looks like a string it should be enclosed with in "", also you will have to make sure that the function select_food is available in global scope

for (var i=0; i<data.length; i++){
    $("#menu").append('<button onclick="select_food("' + data[i]['id'] + '","' +data[i]['name'] + '")>Select</button>)')
}
function select_food(id, name){
     //do something
}

Comments

0

here's a possible solution (see fiddle here http://jsfiddle.net/gDNTw/2/):

$('#menu').on('click', 'button', function() 
{
    var id = this.id;
    var name = this.name;

    alert(id + ':'  + name);
    // do something...
});

for (var i = 0; i < data.length; i++)
{
    $("#menu").append('<button id="' + i + '" name="' + data[i] + '">Select</button>')
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.