views:

47

answers:

2

Hi all!

I have an AHAH-requested HTML, like:

<table>
<tr>
    <td>...</td>
    <td><img src="..." onClick="get_next_ahah(sell####)" id="sell####"/></td>
</tr>
<tr>
    <td>...</td>
    <td><img src="..." onClick="get_next_ahah(sell####)" id="sell####"/></td>
</tr>
... and so on

where #### - numerical IDs from DB. How can I replace the function "get_next_ahah()" on efficient event-written jQuery function? And how can I find out which id I use?

+1  A: 

It would be easier to extract the number from the ID if you separated the number from the prefixed string with an underscore or such, e.g.:

<img src="..." id="sell_1234"/>

Then you would just have to do this:

$('table tr td img').click(function() {
    var num = $(this).attr('id').split('_')[1];
    get_next_ahah(num);
});

If you can't change the ID, then just use a regex instead to extract the number from the string, e.g.:

$('table tr td img').click(function() {
    var num = $(this).attr('id').match(/\((\d+)\)/)[1];
    get_next_ahah(num);
});
karim79
"Also note that you have closed anchor tags, but no opening ones in your markup"sorry, changedThank you for your Answer
+1  A: 

You can use a rather obscure form of CSS selector to grab all elements whose ID contains the text "sell" and then use that to assign events to them:

$("[id^=sell]")

Or, if the elements are all guaranteed to be imgs, you can use this more specific selector instead:

$("img[id^=sell]")

These selectors will both return an array of elements that have "sell" in the ID, which you can call click() on.

To find out the current ID, you can just strip "sell" from the ID and then pass that to your get_next_ahah() function, like this:

$("img[id^=sell]").click(function() {
    get_next_ahah(this.id.replace('sell', '');
});
htw
@htw - +1, funky way of doing it, but note that attribute filters are sloooow.
karim79