2

Here's the problem: I have a list of items on a page, each with its own link/button to delete it. Currently, I have an onclick on each button because each button needs to pass the id and a description/name of the item to a JS function.

I would like to make it less obtrusive, but can't think of a way. Any suggestions?

Here is an example of the current setup:

function doButtonThings(id, desc) {
    //jQuery to do some stuff and then remove the item from the page
}

And the page:

<!-- standard html page stuff -->
<ul>
    <li><button onclick="doButtonThings(1001, 'The thing we delete');"></button> Some thing that can be deleted #1</li>
    <!-- imagine many more list items this way with different ids and descriptions -->
</ul>
<!-- standard end of html page stuff -->
Moismyname
  • 472
  • 1
  • 6
  • 17
  • 1
    You can add a jQuery event handler, and when it's clicked traverse the DOM and get the ID (or even the element) you want. – gen_Eric Nov 17 '11 at 16:17
  • I like this solution for it's raw simplicity. I suppose I could use a name attribute for the description and id for the ID, yes. – Moismyname Nov 17 '11 at 16:27

1 Answers1

3

You can store the data in HTML data attributes:

<button data-myId="1001" data-myDescr="The thing we delete">Click me</button>

And then use them in a jQuery click handler:

$('button').click(function() {
    var $this = $(this),
        id = $this.data('myid'),
        descr = $this.data('mydescr');

    doButtonThings(id , descr );
});

Here is a fiddle to illustrate: http://jsfiddle.net/didierg/fhLde/

Didier Ghys
  • 30,396
  • 9
  • 75
  • 81
  • I like this a lot. Data attributes are an HTML5 feature though, right? I like being on the front edge as much as the next guy, but isn't HTML5 still a draft? I suppose I haven't really done my homework there. All I really care about is that all the current versions of the major browsers support it. If so, I think this is my answer. – Moismyname Nov 17 '11 at 16:26
  • 1
    Data attributes work in all browsers as far as I can remember, pretty sure they even work in IE. :-) – gen_Eric Nov 17 '11 at 16:32
  • 1
    Yep they are part of of the HTML5 specification but this will work in all major browsers though. – Didier Ghys Nov 17 '11 at 16:34
  • Thanks, guys. You've been a great help. Rocket, I'd upvote your answer as well, but it's a comment. :-P ... Nevermind, I can't upvote any. I don't have 15 rep :-( – Moismyname Nov 17 '11 at 16:37
  • While only newer browsers support the special JavaScript property `element.dataset` to access data attributes there isn't anything holding you back for using them on older browsers. Older browsers will just ignore these attributes, but you will still be able to access them via `element.getAttribute('data-...')` or `$(element).attr('data-...')` when using jQuery. jQuery even automatically merges data attributes in it's own `$(element).data(...)` API. – panzi Apr 05 '13 at 17:00