0

I have several blocks of code. The first block adds the users input to the form, the second block tries to grab that data to evaluate a switch statement. Bc javascript reads all scripts once, my var in block two always returns a value of null; the element had no value at the time the .js ran. How do I get the value of an input element created after javascript has read all scripts? Here's a sum of the important parts:

The HTML:

  <div class="form-group">
     <label for="">Weight Classification:</label>
     <input type="text" class="form-control" id="weight-class" name="weight">
   </div> 

The javascript:

<script>
  //prior code grabs height and weight and calcs BMI
  switch (BMI >= 16 && BMI < 43) {
    case (BMI >= 16 && BMI < 22):      
      document.getElementById("weight-class").setAttribute("value", "skinny");    
      break;

    case (BMI >= 22 && BMI < 25):
      document.getElementById("weight-class").setAttribute("value", "average");
      break;

    //other cases here...
     default:
     console.log("Error");
  } 
</script>

Javascript block 2:

<script>
var weight = document.getElementById('weight-class').value; 

  switch (weight) {
    case (skinny):
      console.log("Successful, short");
    break;

    case (average):
      console.log("Successful, average");
    break;

    case (obese):
      console.log("Successful, tall");
    break;

    default:
      console.log("Failed all cases");
    break;
  }

</script>
6
  • > The first block adds the users input to the form, Commented Oct 5, 2020 at 2:41
  • What that mean ❓👆🏽 Normally, with a <form> in JS, we would addEventListener and respond to user interactions such as 'focus' or 'blur' and/or "submit" to do something with the values...😕 Commented Oct 5, 2020 at 2:42
  • The case in block one sets the value of the element Commented Oct 5, 2020 at 2:43
  • 🙆🏽‍♂️ Well, regardless, as you say, the scripts will just run b4 there are 'values' to read. So, AFAIK, we would need to use a callback with an addEventListener...or you could do a 'weird' callback in a setTimeout. Commented Oct 5, 2020 at 2:45
  • 1
    If you want to do something after an input's value has changed, listen for that change. Commented Oct 5, 2020 at 2:48

2 Answers 2

2

You need MutationObserver since you are changing the value of the input via mutating the attribute thus change event handler wont trigger

var weight = document.getElementById('weight-class');
// Create an observer instance with a callback function to execute when mutations are observed
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type == "attributes") {
      let weight = mutation.target.value; // get the value.
      switch (weight) {
        case ('skinny'):
          console.log("Successful, short");
          break;

        case ('average'):
          console.log("Successful, average");
          break;

        case ('obese'):
          console.log("Successful, tall");
          break;

        default:
          console.log("Failed all cases");
          break;
      }
    }
  });
});
// Start observing the target node for attribute mutations

observer.observe(weight, {
  attributes: true //configure it to listen to attribute changes
});
weight.addEventListener('change', function() {
  let weight = this.value;
  console.log('this gets fired when you change the value via input')

})
//lets set the BMI
var BMI = 17 + Math.random() * 7;

switch (BMI >= 16 && BMI < 43) {
  case (BMI >= 16 && BMI < 22):
    document.getElementById("weight-class").setAttribute("value", "skinny");
    break;

  case (BMI >= 22 && BMI < 25):
    document.getElementById("weight-class").setAttribute("value", "average");
    break;

    //other cases here...
  default:
    console.log("Error");
    console.log(BMI);
    
}
<div class="form-group">
  <label for="">Weight Classification:</label>
  <input type="text" class="form-control" id="weight-class" name="weight">
</div>

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

Comments

0
document.addEventListener("change", function(){
  var weight = document.getElementById("weight-class").value; 
 
  switch (weight) {
    case "skinny":
      //do something
      break;

    case "average":
      //do something
      break;
    
    case "obese":
      //do something
    break;

    default:
    console.log("Error");
  }  
});

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.