Is it possible to use .data() as a search criteria?
- by Andrew
I have a pretty complex chat application going on, and there are multiple chat panes, chat entries, chat submits, etc. going on in the same window. At first I was going to do something like....
<input type="text" class="chattext" id="chattext-42">
<input type="text" class="chattext" id="chattext-93">
<input type="button" class="chatsubmit" id="chatsubmit-42">
<input type="button" class="chatsubmit" id="chatsubmit-93">
... etc. (of course this is vastly simplified, they'd be in separate divs, separate visibilities, etc) So, when they clicked on a .chatsubmit, it would then get the id of that and find the last two characters for the chat ID. This presents some problems, as it would require rewrites if IDs changed lengths, and seems just plain inelegant to me.
I then remembered the .data() facility in jQuery... I thought, maybe I could do it more like this:
<input type="text" class="chattext"> ... and add a .data("id", 42) to this one
<input type="button" class="chatsubmit"> ... and add a .data("id", 42)
So that when they click chatsubmit, it gets the ID, and then finds the chattext with that ID and processes it. But looking at the documentation, I don't see an easy way to search by this. For example, let's say the event target in this case is the chatsubmit with the data('id') of 42...
var ID = $(event.target).data('id'); // Sets it to 42
var chattext = ...
And here I run into the trouble. How do I find which DOM element matches a class of chattext and a data('id') of 42? Is there any easy method, or do I have to search every .chattext for the one with an id of 42? Or is there another easy way of doing this?
I did consider the possibility of the container div having the ID, which would make it, I think,? slightly easier to get. But if this works, it could be dealing with things in other container divs as well, making that not a long-term solution.
Edit: Literally seconds after posting this, I found this: http://james.padolsey.com/javascript/extending-jquerys-selector-capabilities/ which includes information on extending the selector to data. So I'll try that out, and in the meantime, is this a completely foolhardy way of handling this?