GOAL: I want the valid icon to show when the input has a valid attribute of true. and the invalid icon to show when it's false && the input has a length of 1 or more characters.
(phoneInputs function): in the console, it outputs "incomplete" for every keypress until the length = 10. When it reaches 10 characters, it says good and sets the valid attribute to true.
(formCheck function): adds or removes a .hidden class depending upon the length. (This is the part that isn't working because I'm trying to target the input's valid attribute. The attribute via the inspector seems to be working and functioning perfectly, via the phoneInputs function)
I've tried console.log() the following:
- input.target - shows the correct input element.
- input.target.valid - undefined
- input.target.getAttribute('valid') - returns an error
Any help?
https://codepen.io/gold240sx/pen/wvyqPpP?editors=1111
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/1758b3260f.js" crossorigin="anonymous"></script>
<style>
.hidden {
display: none;
}
</style>
<script>
const formCheck = (input) => {
const chxVer = input.target.parentElement.querySelector('.bool-form-val')
const validIco = chxVer.querySelector('.check')
const invalidIco = chxVer.querySelector('.x')
if (input.target.getAttribute("valid")==true) {
validIco.classList.remove('hidden')
invalidIco.classList.add('hidden')
} else if (input.target.getAttribute("valid")==false) {
input.target.setAttribute('valid', false)
console.log(input.target.valid)
validIco.classList.add('hidden')
invalidIco.classList.remove('hidden')
} else {}
console.log(input.target.getAttribute("valid"))
}
const phoneInputs = document.querySelectorAll('.phone-number');
phoneInputs.forEach((input) => {
const boolFormChecks = document.querySelectorAll('.bool-form-val');
input.addEventListener('keyup', (e) => {
formCheck(e)
//US numbers only
if (input.value.length === 10) {
input.setAttribute('valid', true)
// console.log(input.target.isValid)
console.log('phone number good')
console.log(input.value) //Outputs final phone number
} else {
// console.log(input.validity.valid)
input.setAttribute('valid', false)
// console.log(input.value.length)
console.log("incomplete")
}
})
})
</script>
<title>Document</title>
</head>
<body>
<div class="input">
<input
type="text"
name="phoneNumber"
id="signup-phoneNumber"
placeholder="Phone Number"
class="icoinput phone-number"
maxlength="10"
>
<div class="bool-form-val">
<i class="fa-solid fa-square-check check hidden"></i>
<i class="fa-solid fa-square-x x hidden"></i>
</div>
</div>
</body>
</html>
formCheckbefore adding the attributevalidto the input. You need to place the function call after you set the attribute.