Nick Seger Nick Seger - 4 years ago 115
HTML Question

Set value of a label using an ID stored in a variable

have searched around and couldn't find anything to answer this problem I'm having.

I have a table in a modal form that will have pre-set prices that are either discount or standard, so I have stored the pricing values in two JS objects. There is also another JS array that has the items that the prices are set too.

When the booking modal opens I have the following loop that runs to go through and populate each item's label with the correct price (whether it is the discounted or standard price is determined earlier).

function bookingPrices(price, ticketType){
for (var i = 0; i < ticketType.length; i++){
for (var index in price){
if (ticketType[i] == index){
var labelID = ticketType[i] + "Price";
$(e.currentTarget).find('label[id=labelID]').text(price[index]);
}
}
}
}


The bit I'm having problems with is I want to use the labelID to correctly populate the intended label with the right price, however I don't think I'm getting the code right to use the labelID variable in the label[id=*] section.

I've tested hard coding the label ID in to make sure I could actually pull the correct key:value data and that is all working, it's just when I use the variable that has the concatenated ID name that it falls over. I'm sure its something syntactically wrong just can't work out what.

Hoping someone could point me in the right direction as to how to go about dynamically setting the ID for the label I want to populate.

Edit: Sorry to those who have already responded, this function is part of a larger JS file that looks after other parts of the booking form.

Thanks

Answer Source

Your code is looking for the ID labelID since you used it as a string.

Replace this:

$(e.currentTarget).find('label[id=labelID]').text(price[index]);

by this:

$(e.currentTarget).find("label[id='"+labelID+"']").text(price[index]);

Since you did not provide any demo, I cant test the whole thing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download