Cleaner code

Do you think that the code below can be written any more cleaner:


We can separate out the parts that are different.

var fieldsInfo = [
  {selector: ".services", name: "service"},
  {selector: ".price", name: "price"},
  {selector: ".price_show", name: "price_show"}
fieldsInfo.forEach(function (fieldInfo) {
  $(fieldInfo.selector + ":visible:first")
    .attr("name", "form[0][" + + "]");

Beyond this, we can use jQuery’s filter which is said to be more efficient:

fieldsInfo.forEach(function (fieldInfo) {
    .attr("name", "form[0][" + + "]");

And we can move the visible and naming parts to a separate function:

function firstVisible(selector) {
  return $(selector).filter(":visible:first");
function setFieldName(field, name) {
  $(field).attr("name", name);
fieldsInfo.forEach(function (fieldInfo) {
  var field = firstVisible(fieldInfo.selector);

There are other optimizations that can be done, but some of the best progress is first achieved by separating that which changes from that which doesn’t.


thanks…these are more than enough

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.