5hakir
5hakir

Reputation: 129

document.getElementById("id").value , change id by adding a variable to it

function totalCost(obj,a){    
  var price = document.getElementById("price").value;             
}

I want to create a new id adding variable a. If a =1, then the next id will be price1. How can I do it?

Upvotes: 0

Views: 766

Answers (2)

5hakir
5hakir

Reputation: 129

function totalCost(obj,a)
     {    
       var price = document.getElementById("price"+a).value;              
     }

this solution is working fine .

Upvotes: 0

Mamun
Mamun

Reputation: 68933

You can use Template Literals which allows embedded expressions:

function totalCost(obj,a){    
   var price = document.getElementById(`price${a}`).value;             
}

OR: Using String Concatenation (if browser is yet to support Template Literals)

function totalCost(obj,a){    
  var price = document.getElementById('price' + a).value;             
}

Upvotes: 1

Related Questions