input.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const validationFieldIDS = ['name', 'email', 'phone']
  2. const BUTTON_ID = 'send_button'
  3. function getGroupInputs(){
  4. return document.querySelectorAll('[input-group="true"]')
  5. }
  6. function getInput(children){
  7. return Array.from(children).find((item) => item.nodeName === 'INPUT' || item.nodeName === "TEXTAREA")
  8. }
  9. function initInput(){
  10. const elems = getGroupInputs()
  11. for(const elem of elems){
  12. const input = getInput(elem.children)
  13. if(input && elem){
  14. elem.onclick = (e) => {
  15. input.focus();
  16. if(elem.classList.contains('active') ){
  17. if(!input.value) {
  18. input.blur()
  19. elem.classList.remove('active')
  20. }
  21. }else{
  22. elem.classList.add('active')
  23. }
  24. }
  25. input.addEventListener('blur', () => {
  26. if(!input.value) {
  27. elem.classList.remove('active')
  28. }
  29. })
  30. }
  31. }
  32. }
  33. function initValidate(){
  34. const button = document.getElementById(BUTTON_ID)
  35. const elems = Array.from(getGroupInputs()).filter((elem) => validationFieldIDS.includes(elem.id))
  36. function validateFields(){
  37. let validatedCount = 0
  38. for(const elem of elems){
  39. const input = getInput(elem.children)
  40. if(input.value){
  41. validatedCount++
  42. }
  43. }
  44. if(validationFieldIDS.length !== validatedCount){
  45. button.disabled = true
  46. }else{
  47. button.disabled = false
  48. }
  49. }
  50. for(const elem of elems){
  51. const input = getInput(elem.children)
  52. input.addEventListener('input', validateFields)
  53. }
  54. validateFields()
  55. }
  56. initValidate()
  57. initInput()