HTML code
<input id="Degree" name="degree" type="number">
JavaScript code
function jsdegree(){
var deg = document.getElementById('Degree').value;
if (deg <73 ) {
alert(" your degree is less than required ");
}
}
But nothing is happening and I did’t Won’t it in submit button , I want it if I write the degree he immediately appears alert box , help me plz :(
CodePudding user response:
From @Rayon comment.
You can use oninput
or onkeyup
events to check on typing.
let degreeInput = document.getElementById('Degree');
degreeInput.oninput = (e) => {
if (e.target.value < 73) {
alert(" your degree is less than required ");
}
};
But.. this JavaScript will be work on every keyboard input. Let's add delay for it.
let degreeInput = document.getElementById('Degree');
let delayTimer;
degreeInput.oninput = (e) => {
clearTimeout(delayTimer);
delayTimer = setTimeout(() => {
if (e.target.value < 73) {
alert(" your degree is less than required ");
}
}, 1000);
};
This will be add delay once keyboard input and wait for 1000 (1 second). If there is no any keyboard input between this the function will be work.
CodePudding user response:
Is that all of your code? If so, the function isn't being called. Someone in the comments suggested an input function, but that wouldn't work if you want the number to potentially be multiple digits. Here are two possibilities:
- This would call every time you press enter ("submitting" the form):
html:
<form onsubmit="jsdegree(event)">
<input id="Degree" name="degree" type="number">
</form>
You could also add, between the first <input>
and the closing </form>
tag, a submit button: <input type-"submit">
and then people could also trigger the event by pressing it.
JavaScript:
function jsdegree(event){
event.preventDefault();
var deg = document.getElementById('Degree').value;
if (deg <73 ) {
alert(" your degree is less than required ");
}
}
Note the event.preventDefault()
is important here, otherwise pressing enter will reload the page.
- This would call every time you click away from the input:
html:
<input id="Degree" name="degree" type="number" onchange="jsdegree()">
And your JavaScript could stay the same.