Cleaner code

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

   $('.services:visible:first').attr('name','form[0][service]');
   $('.price:visible:first').attr('name','form[0][price]');
   $('.price_show:visible:first').attr('name','form[0][price_show]');

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][" + fieldInfo.name + "]");
});

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

fieldsInfo.forEach(function (fieldInfo) {
  $(fieldInfo.selector).filter(":visible:first")
    .attr("name", "form[0][" + fieldInfo.name + "]");
});

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);
  setFieldName(field, fieldInfo.name);
});

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.

2 Likes

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.