Insert variable into html and retrieve value in following function

Hi all,

Here is a simplified example of what I am trying to achieve. I have an HTML table that looks as follows:

<div class="data-table card">
 <table>                        
  <tbody>
   <tr>
    <td class="label-cell">Purchase price</td> 
    <td class="numeric-only" id="purchasePrice"></td> 
   </tr>
  </tbody
 </table>
</div>

When a button is clicked, a value is inserted into the table:

$$('.page-content').find('#buttonInsert').on('click', function (e) {
 var amount= 5;
 $$('.data-table #purchasePrice').html(amount);
});

What I would like to do is retrieve the inserted value from the table when another button further down on the page has been clicked. I have tried:

$$('.page-content').find('#buttonRetrieve').on('click', function (e) {
 var value= $$('.data-table #purchasePrice').val();
 console.log(value);
});

But the console is logging “undefined”. What am I doing wrong?

Instead of declaring…

var amount = 5;

…in the first function. Rather using…

window.amount = 5;

…seems to work as “amount” is now a global variable and can be referenced in the next function. It has solved my issue, but is this the best way to do this?

Disclaimer: I am new to JS :grinning:

why not declaring the var amount=5 in a scope which is reachable from both functions:

var amount = 0;

$$('.page-content').find('#buttonInsert').on('click', function (e) {
 amount= 5;
 $$('.data-table #purchasePrice').html(amount);
});

$$('.page-content').find('#buttonRetrieve').on('click', function (e) {
 console.log(amount);
});
1 Like