Saurabh Kumar
Saurabh Kumar

Reputation: 16651

How can I apply a variable as an element ID with JavaScript?

I saw in the firebug the ID is like this whereas I want the value of existingProductArray[i] to be the ID. What am I doing wrong?

var html ='<li id="existingProductArray[i]">'
       + '<input type="image" id="existingProductArray[i]" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
       + existingProductArray[i]
       + '</li>';
     

Upvotes: 5

Views: 45599

Answers (5)

hanlok
hanlok

Reputation: 19

So I also wanted to declare an div id with a before declared variable and it worked with:

<script>
   let index1 = 1;
   let index2 = 2;
</script>

<div id="prefix"+index1++index2+></div>

so in this case the "prefix" can be anything you want e.g. "Version" and it adds the variables (index1 and index2) to it so the result you'll get is Version12 as the id.

Upvotes: 0

iConnor
iConnor

Reputation: 20189

Try this

 var id = existingProductArray[i];

 var html ='<li id="' + id + '">'
           + '<input type="image" id="' + id + '" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
           + id
           + '</li>';

But

ID hence the name should be unique you are giving 2 elements the same ID ( that's a bad idea )

Upvotes: 7

Sherif elKhatib
Sherif elKhatib

Reputation: 45942

your reference is inside the quotations

       var html ='<li id="'+existingProductArray[i]+'">'
               + '<input type="image" id="'+existingProductArray[i]+'" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
               + existingProductArray[i]
               + '</li>';

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270609

You just need to close the quotes and concatenate it in with +:

var html ='<li id="existingProductArray[i]">'
               + '<input type="image" id="' + existingProductArray[i] + '" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
               + existingProductArray[i]
               + '</li>';

Upvotes: 1

Alex
Alex

Reputation: 9031

Try changing:

+ '<input type="image" id="existingProductArray[i]" src="...>'

to

+ '<input type="image" id="'+existingProductArray[i]+'" src="...>'

So in your line of code it was just using it as text string. You need to break out of the string and do it.

Upvotes: 3

Related Questions