0

I have two dropdown menus and I would like to store the values of the user selected value. I am making use of selectize library for the dropdowns. Html:

 <div style="max-width: 200px">
        <select
          id="dropdown-1"
          multiple="multiple"> 
          <option value="bob">bob</option>
          <option value="mary">mary</option>
        </select>
      </div>

   <div style="max-width: 200px">
        <select
          id="dropdown-2"
          multiple="multiple"> 
          <option value="bread">bread</option>
          <option value="bread">bread</option>
        </select>
      </div>

Javascript:

//variables to store the values
let nameValues = "";
let foodValues = "";

//The selectize library
$(document).ready(function ($) {
  let $market = $("#dropdown-1").selectize({
    sortField: "text",
    placeholder: "Choose a name...",
    onChange: (value) => {
      nameValues += value.join("&");
    },
  });
  let $msm = $("#dropdown-2").selectize({
    sortField: "text",
    placeholder: "Choose a food value...",
    onChange: (value) => {
      foodValues += value.join("&");
    },
  });
console.log(nameValues)
console.log(foodValues)

Putting the console.log(nameValues) and console.log(foodValues) works inside of the onchange function of each. But I want to be able to get the values and use it in another function like this:

const getDropDownValues = (dropval_1, dropval_2)=>{
  console.log(dropval_1 + dropval_2)
}

getDropDownValues(nameValues, foodValues).....

when I console.log each variable it shows empty no value is displayed. what am I doing wrong is there a way to better achieve this?

3
  • Put the console.log(nameValues) inside the onChange method Commented Oct 5, 2022 at 17:05
  • yes it does work, but can it be stored outside that function, I would like to use those two values in another function Commented Oct 5, 2022 at 17:17
  • You have to call getDropDownValues(nameValues, foodValues) after the onChange event of the dropdowns have been triggered. Eg. inside an event listener or something similar otherwise you will get invalid values. Commented Oct 5, 2022 at 18:11

1 Answer 1

0

You can use $market.getValue() and $msm.getValue() outside selectize callbacks at any time. The API documentation for the same can be found here.

Another option you have, is to have two global variables (like you have currently), and inside the change listener, just update global variable values using the latest values. (Although, i don't prefer this, since it means keeping the same values at two places and may cause conflicts/bugs if update is done incorrectly).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.