Sein Kraft
Sein Kraft

Reputation: 8825

change the value of onclick with jquery

Ok, so...i've a button with onclick.

<input id='post-favorite' onclick='Post.Favorite(15,"set");' type='submit' value='Favorite'>

but i need to change the onclick value when it's clicked to Post.Favorite(15,"unset"); there is a way to do that?

Because i've read in some places that is inpossible, intead use onclick use jquery click event.

But the problem is...if i use click event how do i send the values to the event or change them simulating the change of the onclick ?

Also the button is generated by php. If the user already has favorited the image if displays "unset" in the onclick, and if not favorited displays "set" to then when the user do the click set or not the image.

Upvotes: 1

Views: 2233

Answers (4)

gblazex
gblazex

Reputation: 50137

Javascript

var PostFavorite = (function(_state) {
  return function(id, state) {
    _state = _state || state;
    Post.Favorite(id, _state);
    _state = (_state == "set") ? "unset" : "set";
  };
})();

HTML

<input onclick='PostFavorite(15,"set");' id='post-favorite' type='submit' value='Favorite'>

Note: the only thing you've changed in your HTML is that you've removed a dot. How cool is that? :)

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196306

Have a look at the toggle method

$(document).ready(function(){

  $('#post-favorite').toggle(
     function(){Post.Favorite(15,"set");},
     function(){Post.Favorite(15,"unset");}
   );

}

Update (after comments)

Use this wrapper function

function wrapper(elem, id, initial)
{
    var $elem = $(elem);
    var set_state = $elem.data('set_state');
    if (set_state) // invert state
        set_state = (set_state=='set')?'unset':'set';
    else // initialize state
        set_state = initial;

    Post.Favorite(id,set_state);
    $elem.data('set_state', set_state);
}

and use it like

<input id='post-favorite' onclick='wrapper(this, 15,"set");' type='submit' value='Favorite'>

Upvotes: 3

Pavel Strakhov
Pavel Strakhov

Reputation: 40522

Some other suggestion:

var click_action = 'Post.Favorite(15,"set");'
$("#post-favorite").click(function() { eval(click_action); });

You can put some other code in click_action varible, then it will be executed on click action.

Upvotes: -1

a7drew
a7drew

Reputation: 7811

If you want to remove the inline Javascript, you can keep the data in a special attribute and then rely on jQuery for click event handling.

http://api.jquery.com/jQuery.data/

Now you can store the data value with the element, change it and use a simple click event handler to automate it.

Upvotes: 0

Related Questions