Posts tagged safecracker
Anyone out there use ExpressionEngine? Okay, settle down. Anyone use Pixel & Tonic’s Matrix field type? Likely that the same number of people just raised their hands. Now, how many of you custom-dashboard-matrix-using-expression-engine developers also use jQuery?
That should have been everyone as well.
One of the challenges we run into at the office is looking at the values of a Matrix field to compute, compare or validate on. For example, one might have a matrix with this format column format:
Item Description | Price
Very simple data entry example. Item and Price. At any time you might want to get an updated Total Price number to the end user. Looping over the entire Matrix is the pain point we found a nice solution to. Take this jQuery snippet as our reference bit:
$('div#field_id_106 textarea.matrix-textarea[name^="field_id_106[row_"]').filter('[name*="[col_id_38]"]').each(function() {
// Do some cool stuff here with the data. Access the local cell with
// $(this).val()
});
The jQuery warriors among us are saying “Well, yeah, duh!”. The rest of us are looking at Sanskrit. The magic are the name^= and the name*= selectors. First, we select down to the Matrix we care about. In my example, it is contained inside of div#field_id_106. Next I select down to the textarea stuff, since the fields I care about here happen to be textarea fields. Now for some magic.
[name^="field_id_106[row_"]
The operator ^ after the name attribute tells us that the selector we are isolating down to must START with the string field_id_106[row_ in order to be included. Stopping at the row_ is a trick that really made this useful for us. Both NEW matrix rows as well as UPDATE matrix rows (existing values in place) will contain this. You won’t need to know anything about the matrix you are looking at in order for this selector to work.
Last I add the .filter() to our object. This filters further to look at a specific column in the Matrix. I take advantage of the * operator here (can contain ANYWHERE), and I look for the [col_id_38] string in the name attribute. We wrap it up with the .each() call, and now we have a nicely set loop. Within the loop we can get to our cell values with:
$(this).val()
There are going to be a lot of ways to slice this turkey, and I would love to hear from anyone else that has faced this issue. Are there even cleaner ways to get into the Matrix cells via jQuery?
• • •