Jaime Sánchez
Jaime Sánchez

Reputation: 23

Adding variables in Javascript's function

I am trying to clone an td and inserting it to another table adding a new column.. I achieved it, but I can't assign properly a name.. I need to use 2 variables.

console.log("Store Id: "+storeId+"///Product Id:"+newId);

var cloned = $(self).parents('tr').clone();
cloned.find('td').eq(5).after('<td class=""><input type="text" name="product_order_${storeId}_${newId}" id="order_input_cat" value="" class="input-text no-changes" /></td>');  
cloned.appendTo("#products #productOnCatGrid_table tbody");

As you can see, the variables are "storeId" and "newId". The problem is that I can't add it into the name field of <input type....

Thanks a lot, and sorry my bad english :)

Upvotes: 0

Views: 50

Answers (2)

Adrian Lynch
Adrian Lynch

Reputation: 8494

Change the single quotes (') to backticks (`) which will cause an interpolation of those two variables.

Specifically:

.after(`<td class=""><input type="text" name="product_order_${storeId}_${newId}" id="order_input_cat" value="" class="input-text no-changes" /></td>`);

See here if you need more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

For a quick demo run this in the console:

var x = 123
console.log(`What's the number? ${x} is the number!`)

Note: ES6 and up. Check your browser compat. Ignore users on older browsers. VIVA LA ES2016!

If you want to bend over for the older browsers, change this:

...name="product_order_${storeId}_${newId}"...

To this:

...name="product_order_' + storeId + '_' + newId + '"...

sad face

Upvotes: 2

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11388

You can concatenate strings

            cloned.find('td')
                  .eq(5)
                  .after('<td class=""><input type="text" name="product_orden_' 
                       + storeId 
                       + '_' 
                       + newId 
                       + '" id="orden_input_cat" value="" class="input-text no-changes" /></td>'); 

Upvotes: 1

Related Questions