-2
\$\begingroup\$

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.

\$\endgroup\$
  • 5
    \$\begingroup\$ 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. \$\endgroup\$ – George Stocker Sep 22 '15 at 14:52
  • 1
    \$\begingroup\$ Put the body in a named function, and call that function in two .each() loops. \$\endgroup\$ – Barmar Sep 22 '15 at 14:55
  • \$\begingroup\$ Where do you get the i for row[' + i + '] ? \$\endgroup\$ – Wa Kai Sep 22 '15 at 14:56
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Jamal Sep 22 '15 at 19:03
1
\$\begingroup\$

Put the repeated code in a named function so you can call it from both loops.

function addNameAttr(i, subElement) {
    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);
|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.