tora0515
tora0515

Reputation: 2547

how to getElementByID() when the id is a php variable?

For example:

<?php  foreach($something as $anotherthing){  ?>
    <span id="<?php echo $product_id; ?>"><?php echo $price; ?></span>

    <?php if($option == 'select') { ?>
    <select name="joe" id="<?php echo $select_id; ?>" > ......

I have no idea how to get the id's into javascript.

Upvotes: 1

Views: 11275

Answers (4)

xception
xception

Reputation: 4297

Given you use a syntax similar to product-N or product[N] if you only have a want all products on the page:

document.querySelectorAll('[id^=product]');

if you want just one of those you can use only the first match add [0] just before the ;

Upvotes: 1

Giorgi Peikrishvili
Giorgi Peikrishvili

Reputation: 247

The same way as in HTML :

document.getElementByID('<?php echo $id?>');

Upvotes: 2

Quentin
Quentin

Reputation: 944203

HTML is text. JavaScript is text. So - the same way.

getElementById('<?php echo $product_id; ?>');

Upvotes: 7

James
James

Reputation: 5169

Suggestion, either use $_SESSION or put the variable into a hidden input field that always has the same name, then you can get the value from there and use it as the ID :)

Upvotes: 1

Related Questions