1

I'm currently learning JavaScript and I had a few questions as to what was wrong with my code. I'm trying to make a simple age check with the ternary operator and form data. I'm trying to make it so that when the input from the form is under 18, you get the message, and when it is over the button appears. Thanks!

var userAge = document.getElementById("ageInput");
const continueButton = document.getElementById("continue");
function verification() {
    continueButton.style.display = (userAge.value >= 18) ? "block"
: "none";
}
 verification();
 console.log(continueButton.style.display);
<html>
<head>
    <title>test</title>
    <script src="app.js" defer></script>
    <style>
    #continue {
        display: none;
    }
    </style>
</head>
<body>
    <form >
        <span>please enter your age</span>
        <input type="number" id="ageInput"/>
        <input type="submit">
    </form>
    <button id="continue">continue</button>
</body>
</html>

3 Answers 3

1

You need to attach an event to the input. In this example keyup event is added to the input. So on keyup check if the value is greater than 18. Note the use of parseInt and classList

let conBtn = document.getElementById('continue');
document.getElementById('ageInput').addEventListener('keyup', function(e) {
  let ipVal = parseInt(e.target.value,10);
  ipVal > 18 ? conBtn.classList.remove('disableContinue') : conBtn.classList.add('disableContinue')

})
.disableContinue {
  display: none;
}
<form>
  <span>please enter your age</span>
  <input type="number" id="ageInput" />
  <input type="submit">
</form>
<button id="continue" class='disableContinue'>continue</button>

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

3 Comments

Thanks, so I’m guessing that type=“number” on the input type does not define the data type in js but rather is just the way the Input works in html?
it will be of string datatype
Alright, thank you, I’ll try to implement this when I’m free.
0

Add your verification to an event listener for the input

userAge.addEventListener("change", verification);

In this way every time user changes the input your app verifies if he entered number greater than 18. You might also want to check for NaN values. If you want to check the verification on the fly as he is typing use "input" event instead

Comments

0

You need to attach a function to input's input or change event. Like below:

userAge.addEventListener("input", verification, false);

Try it.

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.