Skip to content
Advertisement

Using variable outside of a javascript function

I am redesigning the select dropdown of a site and I am using a jQuery plugin called ddSlick. However, I can’t seem to capture a variable I need outside its function.

In the code below I can’t seem to have the second console.log(build) show what I get in the first console.log(build). I get undefined. What could I be doing wrong?

$(document).ready(function() {
  $("#demo-htmlselect").ddslick({
    width: 300,
    selectText: "Select an item",
    onSelected: function(buildings) {
      let build = buildings.selectedData.value
      console.log(build);
    }
  });

  $("#demo").ddslick({
    width: 300,
    selectText: "Select an item",
    onSelected: function(noises) {
      let nois = noises.selectedData.value
      console.log(nois)
      console.log(build);
    }
  });
});

Advertisement

Answer

You need to define the build variable in scope of both functions:

$(document).ready(function() {
  let build; // define here

  $("#demo-htmlselect").ddslick({
    width: 300,
    selectText: "Select an item",
    onSelected: function(buildings) {
      build = buildings.selectedData.value;
      console.log(build);
    }
  });

  $("#demo").ddslick({
    width: 300,
    selectText: "Select an item",
    onSelected: function(noises) {
      let nois = noises.selectedData.value
      console.log(nois)
      console.log(build);
    }
  });
});

An important note here is that this logic relies on #demo-htmlselect triggering a change event before #demo does. As such, you may need to write some validation logic to deal with this restriction.

With that in mind I would suggest combining the event handlers in to one and checking the state of both dropdowns in there, something like this:

$(document).ready(function() {
  $("#demo, #demo-htmlselect").ddslick({
    width: 300,
    selectText: "Select an item",
    onSelected: doSomething
  });

  function doSomething() {
    let build = $('#demo-htmlselect').val();
    let noise = $('#demo').val();

    // validate both variables have values here...

    // execute whatever business logic is required based on the user input here...
  }
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement