I understand that we live in a mobile-focused world now and onkeyup is not exactly friendly to most mobile browsers' specs so I am trying to remove the attribute below from my html;
<input name="mobile" id="mobile" type="number" required onkeyup="check(); return false;" ><span id="message"></span>
And bind to the on-change event using
$('#mobile').change(function(){ check(); });
But I have no idea how to implement this on my JavaScript.
See my code sample below;
function check()
{
var mobile = document.getElementById('mobile');
var message = document.getElementById('message');
var goodColor = "#03b800";
var badColor = "#f00a0a ";
if (mobile.value.length === 11){
mobile.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Good job! You entered it correctly"
}
else {
mobile.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "required 10 digits, match requested format!"
}}
<input name="mobile" maxlength="11" id="mobile" type="text" required onkeyup="check(); return false;" ><br/><span id="message"></span>
CodePudding user response:
As the Comments already pointed out, you can use the onInputEvent (Inline HTML: oninput=""
), which fires if the Input changes. Although onChange (Inline HTML: onchange=""
) does the same, it only fires if the Focus leaves the input element, which might be too late.
// Alternativly you could add an Eventlistener if the DOMContent is fully loaded. It is practically the same.
//document.addEventListener('DOMContentLoaded', function(){
// document.getElementById('mobile').addEventListener('input', check);
//})
function check()
{
var mobile = document.getElementById('mobile');
var message = document.getElementById('message');
var goodColor = "#03b800";
var badColor = "#f00a0a ";
if (mobile.value.length === 11){
mobile.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Good job! You entered it correctly"
}
else {
mobile.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "required 10 digits, match requested format!"
}}
<input name="mobile" maxlength="11" id="mobile" type="text" required oninput="check()"><br/><span id="message"></span>
CodePudding user response:
<select onchange="myFunction()">
The onchange event occurs when the value of an element has been changed.
For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.
Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed. The other difference is that the onchange event also works on elements