I'm a JS self-learner. Currently jQuery. So please don't downgrade me. I made an age checker app. But the combination input type number submit button only works after a page refresh. Is it possible to change the age after submitting it once and see the style changes without a page reload?
What I mean is that after loading the page, my app works only once. Then console log doesn't show any change in the input field and clicking submit.
<div >
<form>
<label for="age">Check your age</label>
<input type="number" min="5" max="100" id="ageInput" onfocus="this.value=''">
<input id="inpBtn" type="button" value="Submit">
</form>
<div id="underage">
<p>You need to get older. You're underage.</p>
</div>
<div id="ofAge">
<p>You are good to go.</p>
</div>
<div id="tooOld">
<p>You are too old for this club</p>
</div>
let ageInput = document.querySelector("#ageInput").value;
$(document).ready(function(){
$("#inpBtn").click(function(){
console.log(ageInput);
if(ageInput < 18) {
$("#underage").css("color", "red");
console.log("under 18");
} else if (ageInput >= 18 && ageInput < 80) {
$("#ofAge").css("color", "green")
console.log("good to go");
} else {
$("#tooOld").css("color", "gray")
console.log("too old");
}
});
});
CodePudding user response:
The main issue in your code is that you only retrieve the value of #ageInput
once, when the page loads. This means that when your click event occurs it will ignore the value the user typed in to the field.
Also note that as the error messages are hidden until required, you can set their colours once using CSS, and not in JS every time the event happens. Then your code becomes simpler as it just hides/shows the validation error as necessary.
Finally, when working with a form it's better practice to hook your logic to the submit
event of the form. This allows users to submit the form using the return key of their keyboard, amongst other accessibility improvements. To stop the form actually being submit, call preventDefault()
on the event that's passed to the handler as an argument.
Here's a working example with all the above points included:
jQuery($ => {
let $ageInput = $("#ageInput");
$("form").on('submit', e => {
e.preventDefault();
$('.error').hide();
let ageInput = $ageInput.val();
if (ageInput < 18) {
$("#underage").show();
} else if (ageInput >= 18 && ageInput < 80) {
$("#ofAge").show();
} else {
$("#tooOld").show();
}
});
});
.error { display: none; }
#underage.error { color: red; }
#ofAge.error { color: green; }
#tooOld.error { color: gray; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div >
<form>
<label for="age">Check your age</label>
<input type="number" min="5" max="100" id="ageInput" />
<button type="submit">Submit</button>
</form>
<div id="underage">
<p>You need to get older. You're underage.</p>
</div>
<div id="ofAge">
<p>You are good to go.</p>
</div>
<div id="tooOld">
<p>You are too old for this club</p>
</div>
</div>