I have the following line of HTML code to identify a form for JScript purposes:
<form action="/form-to-email.php" method="post" name="helprequest" onsubmit="return validateHelpForm()">
However when I go to validate the web page (via W3C for XHTML Strict), I get the following error message:
there is no attribute "name"
If I have the below JScript code, how can I identify my form. Should I ignore the W3C validation? (This is the only thing not making it W3C valid and works otherwise)
// Text Field Validation
x1 = document.forms["helprequest"]["Name"];
x2 = document.forms["helprequest"]["Mailing_Address"];
x3 = document.forms["helprequest"]["Address_line2"];
x4 = document.forms["helprequest"]["City"];
x5 = document.forms["helprequest"]["State"];
x6 = document.forms["helprequest"]["ZipCode"];
x7 = document.forms["helprequest"]["Country"];
x8 = document.forms["helprequest"]["FromAddress"];
x9 = document.forms["helprequest"]["ProblemDescription"];
x12 = document.forms["helprequest"]["PhoneNumber"];
Use an id
attribute. Just make sure that their value remains unique on a page.
If you wish to identify a set of elements, use the class
attribute.
Both attributes are universal (= may be used on every element).
The Javascript needs an adjustment, though:
function getElementByXpath(path) {
return document.evaluate(
path
, document
, null
, XPathResult.FIRST_ORDERED_NODE_TYPE
, null
).singleNodeValue;
}
x1 = getElementByXpath("/html/body//form[@id='helprequest']//*[@name='Name']");
// ... etc.
This method can be applied to xml documents only ( I assume that is not a problem in your case, since you tagged the question with xhtml; more details here ).
Alternatively you go about like this:
var e_form = document.getElementById("helprequest");
var a_inputs = e_form.getElementsByTagName("input");
for (var i=0; i <= a_inputs.length; i++) {
switch ( a_inputs[i].getAttribute("name") ) {
case "Name": x1 = a_inputs[i]; break;
case "City": x4 = a_inputs[i]; break;
// ...
default:
}
}
Finally, if you decide to use a framework like jquery, you may also write code like this:
x1 = $("#helprequest input[name='Name']")[0]; // element; without '[0]': jquery object
or collect the values directly:
var v1 = $("#helprequest input[name='Name']").val();