0

I'm trying to make form validation but I think my button doesn't work. I did this with paragraph which has "visibility: hidden" style and I want to change it to "visibility: visible" on button click if there is nothing typed in input fields. What can I do to fix it? Here is JS code:

document.querySelector("cta-btn").addEventListener("click", function() {
    let name = document.getElementsByClassName("first-name").value;
    if (name == "") {
        document.getElementsByClassName("name-error").style.visibility = "visible";
        document.getElementsByClassName("first-name").style.border = "1px solid red"
    }
});
  • sorry @HereticMonkey for my bravery of answering a question for the mere goal to help someone, and not to point to his face that somebody has already made a question "that might solve his problem"... I've helped you in your inexorable research of duplicate question by marking this question as duplicate, good luck with your search <3 – Alberto Sinigaglia Aug 28 '21 at 19:31
  • @AlbertoSinigaglia Marking a question as a duplicate helps the OP as much as answering, by directing them immediately (if the duplicate is identified fast enough) to answers to their question, and helps others (which is, after all, the purpose of Stack Overflow, to help many people, not just one at a time) by providing a signpost to those answers should they have the same question. – Heretic Monkey Aug 28 '21 at 19:58
  • @HereticMonkey feel free to report this message to all the people that have answered this question – Alberto Sinigaglia Aug 28 '21 at 20:29

2 Answers2

0

The getElementsByClassName returns an array. if you have only one element with that class that you want to make visible, you can get the first element by accessing 0-index element

document.querySelector("cta-btn").addEventListener("click", function() {
    let name = document.getElementsByClassName("first-name")[0].value;
    if (name == "" || name == null) {
        document.getElementsByClassName("name-error")[0].style.visibility = "visible";
        document.getElementsByClassName("first-name")[0].style.border = "1px solid red"
    }
});
Daniel
  • 1,895
  • 9
  • 20
0

getElementsByClassName("first-name") return an array type not single element, [0] to get 1st match

getElementsByClassName("first-name")[0].value