I am trying to understand the function at (http://www.w3schools.com/js/js_form_validation.asp) and rework it (below) using getElementsByClassName to find a class attribute I added to an HTML input tag. I’m very new to Javascript, and I do not understand why I have to add .value (W3 example) or .view (my example) to the end of the statement below in order for it to work. As I understand it the first statement in the function says look in the document, and assign the variable X, to any input fields with the class attribute reqname.
Thank you.
MY FUNCTION:
function validateForm()
{
var x=document.getElementsByClassName("reqname").view;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
FUNCTION AT W3:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
A form element such as an input field typically has a
value, that is the string that has been entered into the input field.By specifying
.value, they explicitly check whether the content of the element is null. Without it, they’d be checking if the element itself is null, i.e. if the element exists.Your code has some further issues.
.viewthat you’re using doesn’t make sense. Also,getElementsByClassNamereturns a list of elements, rather than a single element, so you won’t be able to immediately access its.value.If you know that there’s just the one element, you could check
getElementsByClassName("reqname")[0].value. If you want to validate the value of all “reqname” fields, you’d have to iterate over your collection and check each item individually: