Issue
Below is an html and Js code that has a list of devices with name and label. I have a drop down menu which is populated with names and an event listener which returns the associated label.
What could be the possible issue?
I am new to javascript and html coding. Apologies if it is a noob question.
const deviceListArray = [
{ createdTime: 1691728083163, name: 'name1', label: 'label 1' },
{ createdTime: 1691725209793, name: 'name2', label: 'label 2' },
{ createdTime: 1691710614954, name: 'name3', label: 'label 3' }
];
const labelSelector = document.getElementById('labelSelector');
// Populate the drop-down menu with all the labels/names
deviceListArray.forEach(entry => {
const option = document.createElement('option');
option.value = entry.label;
option.text = entry.label;
labelSelector.add(option);
});
// Event listener for when a label is selected
labelSelector.addEventListener('change', handleLabelSelection);
let selectedDeviceID;
let deviceIDSelected;
function handleLabelSelection(event) {
const selectedLabel = event.target.value;
const selectedDevice = deviceListArray.find(entry => entry.label === selectedLabel);
if (selectedDevice) {
selectedDeviceID = selectedDevice.name; // Corrected property name to 'name'
} else {
console.log('Device not found for the selected label');
}
// Call a function to perform actions with the updated selectedDeviceID
performActionsWithDeviceID(selectedDeviceID);
}
// Function to perform actions with the updated selectedDeviceID
function performActionsWithDeviceID(deviceID) {
deviceIDSelected = deviceID;
}
console.log(deviceIDSelected);
<label for="labelSelector">Select Device:</label>
<select id="labelSelector">
<option value="">Select device</option>
</select>
Issue is I am unable to log the associated label outside of the function although I have declared it globally.
Solution
Looks like, The console.log(deviceIDSelected)
statement is executed immediately after the script is loaded and before any interaction (like selecting a device from the dropdown) can occur. This means deviceIDSelected has not yet been updated by performActionsWithDeviceID
and still holds its initial value (which is undefined if not explicitly initialized).
To fix this issue, you need to ensure that console.log(deviceIDSelected)
is called after the deviceIDSelected
variable has been updated.
Here is an example code, update performActionsWithDeviceID
function:
function performActionsWithDeviceID(deviceID) {
deviceIDSelected = deviceID;
logDeviceID();
}
function logDeviceID() {
console.log(deviceIDSelected);
}
Answered By - Isha Padalia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.