verlager
verlager

Reputation: 876

How to specify an input id combining a literal and a for loop counter using js?

I have several js for "loops" and I need the cleanest syntax to specity an id value using the "for loop counter". Here is an example that works, but it looks kludgy and it doesn't thrill me much to have to use such janky code. See that:

"USCF_ID' +i +'"' +'

// USCF ID #

items += '<td style="display:none;">
<input onblur="showID();" name = "ID" id = "USCF_ID' +i +'"' +' name = "USCF_ID" /> </td>';

Can you make a suggestion about expressing ID = USCF_ID1 programically in plain js? No jQuery if you can avoid it, please.

Upvotes: 0

Views: 60

Answers (3)

WillWillington
WillWillington

Reputation: 190

It was kind of difficult for me to follow along with your question, but what I got from your explanation is that you're just trying to find a cleaner way to concatenate your data. I would recommend that you use string templates here. Here's an example:

items += `<td style="display:none;">
<input onblur="showID();" name = "ID" id = "USCF_ID${i}" name = "USCF_ID" /> </td>`;

Creating a string with the `...` syntax creates a string template literal that allows you to insert JavaScript code between the ${ } curly brackets and concatenate the result.

Upvotes: 2

Dennis
Dennis

Reputation: 32608

JS itself doesn't have built-in string formatting like other languages (with an exception later). You can simulate it yourself in a simple case like this with the replace method:

template = '<td style="display:none;"><input onblur="showID();" name="ID" id="USCF_ID$i" name="USCF_ID"/></td>';
...
items += template.replace("$i", i);

ES6 has template strings that can do this, but may not be available depending on the browser you are trying to support (note the backticks instead of single quotes):

items += `<td style="display:none;"><input onblur="showID();" name="ID" id="USCF_ID${i}" name="USCF_ID"/></td>`;

Upvotes: 0

Ovidijus Parsiunas
Ovidijus Parsiunas

Reputation: 2742

You can use a string template where "USCF_ID' +i +'"' +' can be replaced by ${id}. String templates are defined using a backtick character - `:

items += `
  <td style="display:none;">
    <input onblur="showID();" name = "ID" id = "USCF_ID${id}" name = "USCF_ID" />
  </td>`;

Additionally you can extract the template into a function:

function getItem(id) {
  return `
  <td style="display:none;">
    <input onblur="showID();" name = "ID" id = "USCF_ID${id}" name = "USCF_ID" />
  </td>`;
}

Then you can generate your list as:

items += getItem(id);

Upvotes: 0

Related Questions