'How to keep variables in JQuery to use later in an event?
I am trying to create a code to fill a form in which the options of some selectors depend on what is selected in a previous selector. I am using the jQuery library to create the events.
I would like to be able to make the event be able to observe the variables even when the code that creates the event has already finished.
Below is an example of what I need to do.
function preValForm() {
App.get('params').then((params) => {
let devices = []
params.devices.forEach(i => { // Here is the params Object { devices: [[...]] , stock: [[...]] }
if (i[0] == "Mobile" && devices.indexOf(i[1]) == -1) { // Not insert duplicates to the array
devices.push(i[1]) // Insert value to array if isn't duplicate
}
})
$('#listDevices').html(devices.map(d => {
return `<option value="${d}">${d}</option>`
}).join('')) // Insert option values to a select element in DOM
// Here is the problem ...
$('#listDevices').on('change', (ev) => { // Create the event when selector #listDevices changes
let stock = [] // Declare variable stock
params.stock.forEach(s => { // ! params is not defined **! -- This is the error**
if (s[1] == ev.target.value && stock.indexOf(s[1]) == -1) {
stock.push(s[1])
}
})
$('#stockOptions').html(stock.map(k => {
return `<option value="${k}">${k}</option>`
}).join(''))
})
})
}
I have seen that this can be done, for example with the SweetAlert2 library you see this behavior where you define an event called preConfirm and when executed the variables are still visible for that event. I would like to be able to do something similar to that behavior, that when I make a change in the selection the event is executed and that event recognizes my variable 'params'.
Thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
