Reputation: 537
I am trying to be super-concise, and have the following javascript code that listens for custom triggered events:
var concat = "";
$("body")
.unbind("__evt_selgrps_ok")
.bind("__evt_selgrps_ok", function(event, param) {
$(param).each( function() {
concat += $(this).attr("data-field-id");
});
});
The event is triggered using code as follows:
$("body")
.trigger('__evt_selgrps_ok',
[$("#<%=DialogID%>").find(":input:checked")]);
Simply, the above gets all the input fields of Checkbox type, that are currently checked, and passes the array of elements as a parameter to the bound handlers (as per the first code example in this question).
Functionaly, this code works well. I just think that there is a lot of code to do something relatively simple, and that is to pass the "data-field-id" attribute values of all checked checkboxes, as a parameter to the trigger.
Ideally, a simple json array of the values passed to the trigger handler would be much better. The trigger handler shouldn't really have to know about the input element, because it just wants to receive the array of attribute values.
I suppose, the bottom-line of my question is, how do you ask JQuery to give you an array of all the specified attribute using a certain selector.
I am only interested in a very nice concise solution, which preferably doesn't involve using the 'each' function.
Thanks! SR
Upvotes: 1
Views: 2372
Reputation: 263077
You can use map() to project an array of attributes from a set of elements:
var fieldIds = $("#<%=DialogID%> :input:checked").map(function() {
return $(this).attr("data-field-id");
}).get();
In your case, you could use it like this:
$("body").trigger("__evt_selgrps_ok",
$("#<%=DialogID%> :input:checked").map(function() {
return $(this).attr("data-field-id");
}).get());
Upvotes: 2