robert trudel
robert trudel

Reputation: 5749

string variable and parameter evaluation

function addRow(){
    var row=`<input name="car[].name">
    <input type='text' name='car[].defaultPrice'></td>
    `;
    $("#carsTable tbody").append(row);  
}

How to pass a concatenate value passed to this function?

if I pass i=0

I would like to get

var row=`<input name="car[0].name"><input type='text' name='car[0].defaultPrice'></td>`;

Upvotes: 0

Views: 66

Answers (3)

LSteenhuis
LSteenhuis

Reputation: 71

var row=`<input name="car[${i}].name">
<input type='text' name='car[${i}].defaultPrice'></td>
`;

assuming you are using ES6, you can use ${i} in order to use the values of variables between the backticks.

Upvotes: 3

Gorka Hernandez
Gorka Hernandez

Reputation: 3958

Making use of string interpolation:

function addRow(i) {
    var row=`
        <td>
            <input name="car[${i}].name">
            <input type='text' name='car[${i}].defaultPrice'>
        </td>`;
    $("#carsTable tbody").append(row);  
}

Regular string:

function addRow(i) {
    var row="<td>" +
                "<input name='car[" + i + "].name'>" +
                "<input type='text' name='car[" + i + "].defaultPrice'>" +
            "</td>";
    $("#carsTable tbody").append(row);  
}

Though, if you want the name property to evaluate to the actual content of car[i].defaultPrice and name, you will need to do the following:

var car = [
    { name: 'Test', defaultPrice: 20000 },
    { name: 'Test2', defaultPrice: 25000 }
];

function addRow(i) {
    var row=`
        <td>
            <input name="${car[i].name}">
            <input type='text' name='${car[i].defaultPrice}'>
        </td>`;
    $("#carsTable tbody").append(row);  
}

Then call the function:

addRow(0);
addRow(1);

Upvotes: 3

wscourge
wscourge

Reputation: 11291

Pass the desired number as an argument to the function:

function addRows(number) {

    var row = '' +
        '<td>' +
            '<input name="car[' + number + '].name">' +
            '<input type='text' name="car[' + number + '].defaultPrice">' +
        '</td>';

    $("#carsTable tbody").append(row);

}    

Upvotes: 1

Related Questions