skip to Main Content

I have a Package Class where a random ID is given at the beginning and a package type can be chosen afterwards.

It seems, that the values are given correctly. I can click between package and letter.But when the method chooseType has been called the second time, the program stops executing, after the method returned the value. The console is not logging the "typeOfPackage". Any suggestions would be appreciated.

//Generate PackageId 
let generateID = () => {
  return Math.random().toString(36).slice(2)

}

// choose type of element to be sent
var e = document.getElementById("selectPackageType");
let chooseType = () => {
  var value = e.value;
  return value;
}

const randomID = generateID();
console.log(randomID);

e.onchange = chooseType;
const typeOfPackage = chooseType();

if (typeOfPackage == null) {
  console.log("type of packege is null")
} else {
  console.log(typeOfPackage);
}
<form autocomplete="off">
  <label for="selectPackageType">Type:</label>
  <select id="selectPackageType">
    <option value="1">letter</option>
    <option value="2">package</option>
  </select>
</form>

4

Answers


  1.  //Generate PackageId
          let generateID = () => {
            return Math.random().toString(36).slice(2);
          };
    
          // choose type of element to be sent
          var e = document.getElementById("selectPackageType");
          let chooseType = () => {
            var value = e.value;
            const randomID = generateID();
            console.log(randomID);
    
            const typeOfPackage = value; // can be remove this extra variable by using value direct itself
    
            if (typeOfPackage == null) {
              console.log("type of packege is null");
            } else {
              console.log(typeOfPackage);
            }
            return value;
          };
    
          e.onchange = chooseType;`enter code here`
    
    Login or Signup to reply.
  2. chooseType doesn’t actually do very much, so even though it’s getting invoked every time you change the dropdown, there are no observable side effects to help you see that that’s the case. You can either change chooseType itself to do all the things you want to have done, or use a different function as your callback.

    //Generate PackageId 
    let generateID = () => {
      return Math.random().toString(36).slice(2)
    
    }
    
    // choose type of element to be sent
    var e = document.getElementById("selectPackageType");
    let chooseType = () => {
      var value = e.value;
      return value;
    }
    
    const randomID = generateID();
    console.log(randomID);
    const updateType = () => {
        const typeOfPackage = chooseType();
    
        if (typeOfPackage == null) {
          console.log("type of packege is null")
        } else {
          console.log(typeOfPackage);
        }
    }
    // set things up based on the initial selection
    updateType();
    // set things up again any time the selection changes
    e.onchange = updateType;
    <form autocomplete="off">
      <label for="selectPackageType">Type:</label>
      <select id="selectPackageType">
        <option value="1">letter</option>
        <option value="2">package</option>
      </select>
    </form>
    Login or Signup to reply.
  3. Yes, @StriplingWarrior fixed the important issues. But the whole thing can be done in three lines:

    document.getElementById("selectPackageType").onchange=ev=>
      console.log(ev.target.value??"type of package is null");
    console.log(Math.random().toString(36).slice(2));
    <form autocomplete="off">
      <label for="selectPackageType">Type:</label>
      <select id="selectPackageType">
        <option value="1">letter</option>
        <option value="2">package</option>
      </select>
    </form>
    Login or Signup to reply.
  4. As I explained in a comment to the question, the bug is that everything from const typeOfPackage = selectType() is only executed ONCE, when the script is run for the first time, regardless of what you choose in your elements.


    I will here provide a few more points that I hope you will find helpful.

    let generateID = () => {
      return Math.random().toString(36).slice(2)
    }
    

    I don’t understand why you use an arrow function to declare generateID . If you really want to declare the function this way, my recommendation is to do it with const, no curly brackets nor return:

    const generateID = () => Math.random().toString(36).slice(2);
    

    But I prefer a normal function:

    function generateID() {
      return Math.random().toString(36).slice(2);
    } 
    

    Next is your chooseType function, which is called as an event handler when the element has changed. First, I renamed it "updatedType" and declared it as a normal function instead of an arrow function. This makes this a reference to the element that called the function, making it possible to use the same function to several different elements. I also moved the code that prints the value into this function, so that piece of code is executed when the element is changed. Since it’s an event handler called by the element, there’s no need to return a value, so I removed the return statement.

    function updatedType() {
      var value = this.value;
      if (value == null) {
        console.log('type of packege is null');
      } else {
        console.log(value);
      }
    }
    

    There are several ways to add an event handler to an element. The onchange you used is one of them and works just fine in small projects. The main disadvantage of that method is that it is only possible to have one event handler attached to the element. It’s not a problem in small projects, but in larger projects you may want to have more than one event handler on the same element, and for that there is addEventListener.

    document.getElementById('selectPackageType').addEventListener('change', updatedType);
    

    Worth noting is that if there is no element with id "selectPackageType" the code will stop executing with an error message. In larger projects, you hopefully use some library that handles it for you and minimizes what you need to write.

    I hope you find my comments helpful and I wish you the best of luck in your future programming adventures.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search