0

I have links that sends submitTask(takk, layout) function (its my own function that she add values to form and send it). I want combine this function with jQuery. I've made something like this.

$(function() {
    $('#edit').click(function(e) { 
        e.preventDefault();
        submitTask('edit','edit');
    });
});

for

<a href="#" id="edit">Link</a>

It works but I want to change that jQuery function in universal for all a elements I want (I don't want to define $().click() for each element in script) function that will be called onclick like this:

<a href="#" onclick="jqueryFunction('task','layout')>Link</a>

Because I still want to keep .preventdefautlFunction(). I don't know how to jQuery function with params. I need something like this but working properly:

function jqueryFunction(task,layout){
$('a').preventDefault();
submitTask(task,layout);
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Sheryf
  • 71
  • 2
  • 13
  • 1
    Have a look at this: http://stackoverflow.com/questions/12093192/how-to-create-a-jquery-function – Pieter Jul 24 '13 at 11:20

1 Answers1

1

Actually, using obtrusive event handlers is generally bad practice - you're better off going with your first example, and then using a class to handle the click.

For example your markup could be changed to:

<a href="#" class="customClick" id="edit">Click Me</a>

And then your jQuery code would look something like this:

$('a.customClick').on('click', function(e) {  
    e.preventDefault();
    var action = $(this).prop('id');
    submitTask(action, action);
});

If you need to define a layout that is different from the action, use a switch() statement:

$('a.customClick').on('click', function(e) {  
    e.preventDefault();
    var action = $(this).prop('id'),
        layout;

    switch(action)
    {
        case 'edit':
            layout = 'edit';
            break;
    }
    submitTask(action, layout);
});
BenM
  • 52,573
  • 26
  • 113
  • 168
  • But what if i want to get more than 1 attribute, in my example both are 'edit' but if they are difference.Theres only 1 id. How to resolve that? – Sheryf Jul 24 '13 at 11:22
  • Use a `switch` statement and then assign `layout` depending upon the ID of the clicked element. – BenM Jul 24 '13 at 11:22
  • It's working but i dont like that in jQuery xD. Maybe because im starting to use that and im not used to this way of programing. Thanks for help. – Sheryf Jul 24 '13 at 11:36