-2

I'm trying to validate some code via javascript. The drama I am having is that I receive an

"Uncaught TypeError: Cannot set property 'border' of undefined".

I am new to javascript and trying to get a full understanding of why this happens and how to prevent this in future coding projects. My goal is if the validation fails it changes the text box border to red.

function validation_Step1(event) {
    var Firstbox = document.getElementsByName("Firstbox");

    if (Firstbox.value == null || Firstbox.value == '') {
        document.getElementsByName("Firstbox")
            .style.border = "2px solid red";
        alert("Error");
        return false;
    } else {
        return true;
    }
}
Fadhly Permata
  • 1,686
  • 13
  • 26
Buzzy
  • 45
  • 7
  • 6
    getElementsByName does not return a single element, but a NodeList - so you have to access the element(s) inside it individually, for example using the index notation. – CBroe Sep 26 '16 at 10:32
  • [`getElementsByName`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName) Returns a nodelist collection... – Rayon Sep 26 '16 at 10:32
  • is there any element with attribute name as `Firstbox` ? – Aatif Bandey Sep 26 '16 at 10:32

2 Answers2

2

It's because document.getElementsByName("Firstbox") returns a NodeList which can be seen as a "kind of" array.

You should do document.getElementsByName("Firstbox")[0] if you want to manipulate the first element only

Molochdaa
  • 2,158
  • 1
  • 17
  • 23
  • _"returns an array"_ ? No, it is not an `array` – Rayon Sep 26 '16 at 10:34
  • The object it returns has many things in common with an array, but it definitely isn't one. – Quentin Sep 26 '16 at 10:34
  • Ok, it's a NodeList, but for a begginer, the difference are not really meaningful. Anyway, I'll change my answer to be more specific. – Molochdaa Sep 26 '16 at 10:39
  • Thanks, I got it working, however when i try to assign the value of the box to check the string(input) it won't retrieve the value. I used alert to see what was in this and it alerts [ObjectNodeList]. I have tried to retrieve the value from the node list but not much luck.. – Buzzy Sep 27 '16 at 10:00
-2

To find elements use ids:

<input type="text" id="login">

Then get the element:

var elem = document.getElementById('login');

Also run JS scripts when whole HTML has been loaded, use onload event in JS.

Marcin
  • 1,488
  • 1
  • 13
  • 27