-1

Is is possible to increment javascript variables. I have a table that gets information from a database which then displays an edit option, once clicked it shows the user and then a drop down for a bunch of products to assign to that user. Once the user clicks on a product then it displays the price of that product. Now each entry needs to have a unique ID, which i succeeded by incrementing the ID's in the script, however the variables also need to change, this will eliminate me having to type out the script each time.

For this case here is the script and what i have tried. Just not successful on incrementing the variable names.

Note that the ID's gets populates with the ID's from the database. So it would be product_info1, product_info2 and the price would be price1, price2 and so on. Just the program does not want to work with the same variable names.

HTML

<table>
<tr>
    <th>Name</th>
    <th>Surname</th>
    <th>Phone Number</th>
    <th>Gender</th>
</tr>

<?php

$sql = "SELECT * FROM test_table";
$result = $db->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {
?>

    <tr>
    <td><?php echo $row["name"]; ?></td>
    <td><?php echo $row["surname"]; ?></td>
    <td><?php echo $row["phone_number"]; ?></td>
    <td><?php echo $row["gender"]; ?></td>
    <td><ul class="t-dropdown-list">
    <a data-toggle="modal" data-target="#SetProductCustomer<?= $row["id"]; ?>"><li class="t-dropdown-item">Edit</li></a>
        </ul></td>
    </tr>

   <div class="modal fade" id="SetProductCustomer<?= $row["id"]; ?>" class="" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" aria-hidden="true">
     <div class="modal-content">
        <a href="test.php"><span class="close">&times;</span></a>

           <p><?php echo $row['name']; ?> </p>

           <select style="width: 100%;" name="" id="product_info<?= $row["id"]; ?>" class="browser-default custom-select-new">

           <?php
           $records = mysqli_query($db, "SELECT * FROM products");    
              while ($data = mysqli_fetch_array($records)) {                                             
              echo '<option value="' . $data['product_name'] . '"
              data-price="' . $data['price'] . '"  >'
              . $data['product_name'] . '</option>';
            }

           ?>

         </select>

         <input type="text" name="price" id="price<?= $row["id"]; ?>"/>

            </div>
        </div>
      <?php
      }
   }
?>
<script>

for(var i=1; i < 4; i++){

var mySelect = mySelect + i;
var myNewOption = myNewOption + i;

mySelect = document.getElementById("product_info" + i);

mySelect.addEventListener("change", function() {
myNewOption  = mySelect.options[mySelect.selectedIndex].getAttribute("data-price");

document.getElementById("price" + i).value = myNewOption;

});

}

</script>
  • you are overriding mySelect and myNewOption, so the 2 first statements (inside the loop) can be omitted, and since myNewOption is not used outside the callback you can move its definition inside it, then var declares a function scoped variable while you need to keep the reference of the value of the current iteration, in this case you need to replace var mySelect by let mySelect – Ahmed Lazhar Jul 28 '22 at 06:38
  • you have some confusion in your js.. if you share the html it will be easier to give you very spot on suggestions.. otherwise you'll have to deal with the word "scope" that it's still out of your understanding. But in general, inside your event handlers, don't rely on variables defined in a different scope.. always rely on window.event.target and fetching elements from scratch from dom – Diego D Jul 28 '22 at 06:41
  • I had the chance to see the html you included in the question.. but I couldn't understand clearly your problem so I don't know how to help you. You describe the problems in terms of how you approached to it with your solution (X/Y problem). The title itself is a dumb question. How do you increment a variable? easy: a = a+1; or a++; but of course that's not what you are looking for – Diego D Jul 28 '22 at 07:06
  • Hi @DiegoDeVita, thank you for your feedback, I am aware that the structure is all wrong and i could have maybe questioned it differently. If i had to code out each script with different variables, and with the correct ID's then it works fine. So my approach was to create a for loop that changes the ID's and the variables within the loop, thus without having to hard code everything. Can you perhaps give an example in code to see where i am going wrong. Thank you. – Gareth159753 Jul 28 '22 at 07:18
  • You can use ``eval()`` to store code in variables: https://stackoverflow.com/questions/18269797/what-does-eval-do-and-why-its-evil – Bjop Jul 29 '22 at 12:16

3 Answers3

1

This is the correct way to have a change event handler on your dropdown that will update the price of the selected item showing it on the input box below:

const mySelect = document.getElementById("product_info");

mySelect.addEventListener('change', (event) => {   
  const optionSelected = event.target.querySelector(':checked');
  const price = optionSelected.dataset.price;  
  document.getElementById('price').value = price;      
});
<select style="width: 100%;" name="" id="product_info" class="browser-default custom-select-new">
  <option value="Gibson" data-price="2500">Gibson</option>
  <option value="Drums" data-price="35000">Drums</option>
</select>

<input type="text" name="price" id="price" value="" />
Diego D
  • 6,156
  • 2
  • 17
  • 30
0

All i changed was the var to let in the for loop and that solved my problem. Thank you for all the comments.

<script>

for(let i=1; i<10; i++) {
let mySelect = document.getElementById("product_info" + i)

mySelect.addEventListener("change", () => document.getElementById("price" + i).value = mySelect.options[mySelect.selectedIndex].getAttribute("data-price"))

console.log(mySelect);

}

</script>
-1

In this case i would do sommething like this:

for(let i=1; i<10; i++) {
    let mySelect = document.getElementById("product_info" + i)

    mySelect.addEventListener("change", () => document.getElementById("price").value = mySelect.options[mySelect.selectedIndex].getAttribute("data-price" + i))
}
<select style="width: 100%;" name="" id="product_info" class="browser-default custom-select-new">

  <option value="Gibson" data-price="2500">Gibson</option>
  <option value="Drums" data-price="35000">Drums</option>


</select>

<input type="text" name="price" id="price" value="" />
Bjop
  • 330
  • 4
  • 19
  • as I tried to explain in my comment above .. you also have confusion with scopes.. but inside an answer it has a different weight! mySelect will change at each iteration but you still rely on it inside your event handler that will be executed by the events loop. that's wrong and you should use window.event.target to know the element triggering the event. This answer deserves a downvote – Diego D Jul 28 '22 at 06:46
  • @Bjob, i tried adding your code to mine and it displays as "undefined" in the price input field for all the products, however i can see the data-price (price) when i inspect the dropdown options. – Gareth159753 Jul 28 '22 at 06:56
  • @Gereth can you place an example of the html code without the php stuff, this so I can test it. – Bjop Jul 28 '22 at 06:59
  • Hi @DiegoDeVita, i added the HTML to the OP. My apologies for the poor javascript structure, still in the learning phase. – Gareth159753 Jul 28 '22 at 07:00
  • @Bjop, i posted an answer where the values, are shown as undefined. I did this without the loop, as the ID's are populated with ID's from the database that increments each time. I am sure if we can sort out that is shows the correct values that the loop will work correctly. – Gareth159753 Jul 28 '22 at 07:46
  • @Gareth I edited my answer and placed it in a snippet so you can test it – Bjop Jul 28 '22 at 07:59
  • Hi @Bjop, so my issue now is that the row does not collect the rows details, it keeps on using the first rows ID, whereas i need each row to be unique, and have it display that rows details. When i remove the = $row["id"]; ?> from the modal callback, it displays all the prices on all the rows, but it does not display the users information, which i need. When i add = $row["id"]; ?> to the modal call back then it displays the users information but only works on the first row when selecting a product and not on the others. – Gareth159753 Jul 28 '22 at 09:03
  • Why dont you work with arrays, than you ask all rows in an array and you do not need to give them an id – Bjop Jul 28 '22 at 09:22
  • Hi @Bjop, i sorted it out thank you, i posted the answer with your solution, i am pretty sure you original post had the let in instead var. Thank you – Gareth159753 Jul 28 '22 at 09:35