# Shorten jQuery code

Is it possible to shorten the following jQuery code into one single block? At the moment, the current code is 2 blocks, but it is practically identical. I tried adding .break-row to the first selector but this then results in the incorrect value of k.

$(div).find('.overtime-row').each(function(k, subRow) { // get all fields$(subRow).find('input, select').each(function(l, subElement)
{
var inputName = $(subElement).attr('data-name'); var parts = inputName.split(':');$(subElement).attr('name', 'row[' + i + '][' + parts[0] + '][' + k + '][' + parts[1] + ']');
});
});

$(div).find('.break-row').each(function(k, subRow) { // get all fields$(subRow).find('input, select').each(function(l, subElement)
{
var inputName = $(subElement).attr('data-name'); var parts = inputName.split(':');$(subElement).attr('name', 'row[' + i + '][' + parts[0] + '][' + k + '][' + parts[1] + ']');
});
});

Can anyone advise if this is possible? I'm just looking to keep clean code.

• The problem with this question is two-fold: 1) It's not written well enough so that someone else with a similar question would be able to find this one, 2) No one ever searches google for "shorten JQuery Code" (and if they did; should they find this question every time?) 3) This should be asked on Code-Review if you don't have an actual problem with the code. – George Stocker Sep 22 '15 at 14:52
• Put the body in a named function, and call that function in two .each() loops. – Barmar Sep 22 '15 at 14:55
• Where do you get the i for row[' + i + '] ? – Wa Kai Sep 22 '15 at 14:56
• The desire to improve code is implied for all questions on this site. Question titles should reflect the purpose of the code, not how you wish to have it reworked. See How to Ask. – Jamal Sep 22 '15 at 19:03

var inputName = $(subElement).attr('data-name'); var parts = inputName.split(':');$(subElement).attr('name', 'row[' + i + '][' + parts[0] + '][' + k + '][' + parts[1] + ']');
$(div).find(".overtime-row").each(addNameAttr);$(div).find(".break-row").each(addNameAttr);