-1

I have 27 buttons (A-Z and All) and need to pass the value in order to filter the REST API (i.e. If "A" button is clicked, filter list with Last Name starts with "A" and so on.

below is my current HTML marking:

<div id="btnPDContainer">
<button class="btnPD active" type="button" onclick="myFilter('All', this)"><i class="fas fa-users"></i></button>
<button class="btnPD" type="button" onclick="myFilter('A', this)">A</button>
<button class="btnPD" type="button" onclick="myFilter('B', this)"">B</button>
<button class="btnPD" type="button" onclick="myFilter('C', this)"">C</button>
<button class="btnPD" type="button" onclick="myFilter('D', this)"">D</button>
<button class="btnPD" type="button" onclick="myFilter('E', this)"">E</button>
</div>

Javascript:

var filterByValue;
var myFilter = function(value, object) { 
    object.innerHTML = value; 
    filterByValue = value;
};
console.log(filterByValue);

If I insert the console log within the function it works but it doesn't work if I use the variable filterByValue in REST API. If I place it outside, like above, it gives undefined error.

Tamras Merin
  • 159
  • 1
  • 8
  • well think about it.... the consoe.log line runs BEFORE the function runs. The code after it does not sit and wait for the function to be called.....The console line would need to sit inside the function.... – epascarello Feb 19 '19 at 20:55
  • That i didn't know. But @ellipsis explained it wonderfully. – Tamras Merin Feb 19 '19 at 21:17

1 Answers1

1

The myFilter function runs onclick of the button but console.log will run as soon as the code reaches it. So as soon as the program run console.log prints the value of the variable which is initially undefined. Call another function from the onclick function which prints the value off the variable

var filterByValue;
var myFilter = function(value, object) { 
    object.innerHTML = value; 
    filterByValue = value;
    a();
};
function a()
{
console.log(filterByValue);
}
<div id="btnPDContainer">
<button class="btnPD active" type="button" onclick="myFilter('All', this)"><i class="fas fa-users"></i></button>
<button class="btnPD" type="button" onclick="myFilter('A', this)">A</button>
<button class="btnPD" type="button" onclick="myFilter('B', this)">B</button>
<button class="btnPD" type="button" onclick="myFilter('C', this)">C</button>
<button class="btnPD" type="button" onclick="myFilter('D', this)">D</button>
<button class="btnPD" type="button" onclick="myFilter('E', this)">E</button>
</div>
ellipsis
  • 12,049
  • 2
  • 17
  • 33