Forum Moderators: open

Message Too Old, No Replies

name to id

upgrading form name to id for xhtml strict

         

nyteshade

1:54 pm on Jun 10, 2011 (gmt 0)

10+ Year Member



I am learning js and am currently converting js to xhtml strict, so, I need to eliminate the deprecated
form 'name' attribute and replace it with the 'id' attribute. For example:
//html-the old way
function checkForm(){
var myForm = docoument.form1

if (myForm.txtAge.value =="" || myForm.txtName.value =="")
{
alert("Please complete all the form.");

if (myForm.txtName.value =="")
{
myForm.txtName.focus();
}
else
{
myForm.txtAge.focus();
}
.
.
etc...
}

<form name="form1">
<input type="button" onclick="checkForm()" />


//xhtml-conversion
function checkForm(){
var myForm = docoument.forms["form1"] <----- not working? but you get the idea?
.
.
.
}

<form id="form1">
<input type="button" onclick="checkForm()" />


What I think I understand is that the //html version: var myForm = document.form1 creates an object in myForm that allowed me to access the form elements as properties, yes?

If I then understand correctly, replacing 'name' with 'id' in //xhtml I should be able to access the form from the forms array but my line is not creating an object in the var myForm. I think its just creating a reference?

Can someone explain what is happening AND how to use the form id to get my not working line to work OR where to go to find a complete list of DOM stuff/properties/subojects and form/id stuff.
Thanking you in advance!

rocknbil

5:42 pm on Jun 10, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Before commenting one has to ask **why** you need to convert to XHTML strict. Are you using any XHTML features? Is your output just plain old vanilla HTML? XHTML is not "better" in any sense, an HTML doctype better describes the content if your document is HTML. XHTML is also in a decline, HTML5 is now the darling debutante. :-)

That being said, the principles you're trying to achieve work equally well in HTML as they do in XHTML. The "name" attributes are not deprecated for form elements, they are deprecated for any non-form elements - but using ID's in your documents is a better approach anyway, whatever doctype you need.

Just compare my revisions against yours, they should work fine. (Though untested - debug it if need be. :-) )


// I left in a reference to the form in this example,
// but WE'RE NOT EVEN USING IT. Note how it's passed
// via the onsubmit handler - but we don't need it for
// what we're doing here.
function checkForm(form){
// Just an example of using the form parameter.
// You could refer to fields as form.txtAge, etc.
// if you wanted to.
var required = {
'txtAge':'Age',
'txtName':Name',
'some-other-field':'Other Value'
};
var msg = '';
for (key in required) {
if (documentGetElementById(key).value=='') {
msg += "The " + required[key] + " field is required.\n";
}
if (msg=='') { return true; }
else { alert(msg); return false; }
}

<form name="form1" id="form1" onsubmit="return checkForm(this);">
<!--
Per my notes above - we don't need to pass the reference to the form. We can just do
<form name="form1" id="form1" onsubmit="return checkForm();">
-->
<p><label for="txtAge">Age:</label> <input type="text" name="txtAge" id="txtAge"></p>
<p><label for="txtName">Name:</label> <input type="text" name="txtName" id="txtName"></p>
<p><label for="some-other-field">Some Other Value:</label> <input type="text" name="some-other-field" id="some-other-field"></p>
<input type="submit" value="Submit">
</form>

Some notable changes:
- Move the event handler to the form submit. You do, after all, want to insure the submit is what you capture, not the button click.
- Use input type="submit", not a button, your form will fail without Javascript. This insures it works with it disabled (you should be duplicating these validations server side to insure this.)
- By returning false from the function on failure, this stops the form from submitting. Same is true of links, for actions handled by JS, you return false onclick to stop them from navigating.
- the document.getElementById method is much easier to use, as you can see.
- The object we construct in the function is similar to an associative array (though it's not an array at all.) This allows us to use "plain English" messages in the alert for our not-so-friendly field names/id's.
- By iterating through the array of fields, you collect **all** messages at once in a single alert:

---------
The Age field is required.
The Name field is required.
The Other Value field is required.
---------

This gets rid of one of my personal annoyances, alert one. Error. At. A. Time. :-)

All of these methods apply to HTML, XHTML, or HTML5 doctypes.

nyteshade

10:25 pm on Jun 10, 2011 (gmt 0)

10+ Year Member



Thanks rocknbil for the detailed reply. I am still learning and was just following a simple example from a text but the nice thing was that I understood everything you said and I was able to follow your example (that code was slick as poop through a goose, thanks!). I'm also learning XML from Beginning XML 4th edition and from what I thought I knew, XML and XHTML are the future (whatever that means) so I've been trying to keep my code up to w3c standards. I understood that most name attributes are deprecated in HTML5 save for the one in the input element (even the one for the form element according to w3schools) but I'm just a nube so I can be easily fooled, once, maybe twice.

Anyways, here is what I got thanks to you. It ain't pretty but it works far as I can tell.

<html>
<head><title></title>
<script type="text/javascript">
function checkForm()
{
//creates an array-like object
var required = {
'txtName' : 'Name',
'txtAge' : 'Age'
}
var msg='';

//sweeps the required object
for (key in required)
{
if (document.getElementById(key).value=='')
{
msg += "The " + required[key] + " field is required.\n";
}
}

if(msg=='')
{
//isNAN sucks
x = parseFloat(document.form1.txtAge.value)
if (x*0!==0)
{
msg += "Please enter a valid age";
document.form1.txtAge.focus();
document.form1.txtAge.select();
}
}

//submits to server on true; not on false
if(msg=='') {return true;}
else {alert(msg); return false;}
}
</script>
</head>

<body>
<!-- default method attribute value is 'get' -->
<form name="form1" id="form1" onsubmit="return checkForm();">
<p><label for="txtName">Name:</label><input type="text" id="txtName" name="txtName" /></p>
<p><label for="txtAge">Age:</label><input type="text" id="txtAge" name="txtAge" size=3 maxlength=3 /></p>
<input type="submit" value="submit" />
</form>
</body>
</html>

JAB Creations

8:49 pm on Jun 11, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



XHTML is the way to go presuming you're serving XHTML as application/xhtml+xml...

<?php
if (isset($_SERVER['HTTP_ACCEPT']))
{
$mime = stristr($_SERVER['HTTP_ACCEPT'],'application/xhtml+xml');
}
else {$mime = 'text/html';}

if ($mime) {$mime = 'application/xhtml+xml';}
else {$mime = 'text/html';}

header('Content-Type: '.$mime);
?>


There simply is no reason to use HTML and text/html. By using XHTML you'll strengthen your everyday coding habits and the only thing that could get by the XML parser are duplicate ID's. If you want to consider the benefits of HTML5 simply use HTML5 element names for XHTML classes instead.

Forms can be confusing in the id/name attribute context. The easiest way to figure out what you're doing is to create a form that submits via the POST method and use PHP to display what it saw from the form...

<div><pre>
<?php
print_r($_POST);
?>
</pre></div>


You use the id attribute for JavaScript and label association...

<div><label for="form_id_1">Label Text</label><input id="form_id_1" name="form_id_1" type="text" value="" /></div>


The name is what PHP will use from the form field.

To maintain maximum compatibility due to an older IE bug it's good practice to make sure that the values of both the id and name attributes are the same (e.g. id="field1" name="field1").

You can use the name attribute on buttons as well. In example if you want to determine if the user wants to preview or publish a forum post you would simply add name="preview" or name="publish" for the submit buttons. Then in PHP you would use isset($_POST['preview']) to determine which action to the user chose.

To access the values of form fields you can use JavaScript as so...

alert(document.getElementById('form_id_1').value);


You can also save a form field to an ID and refer to it however if you want to change a form field's value in example you'd have to use the object directly...

var a = document.getElementById('form_id_1');
alert(a.value);

//change form value? Use object directly...
document.getElementById('form_id_1').value = 'oh hai!';


If you're having trouble with JavaScript types you can determine what kind of object you have using typeof...

var a = document.getElementById('form_id_1');
alert(typeof a.value);


I have seen no reason to use the name attribute on a form element directly, not sure it'll even be submitted to the server offhand (it might, use isset() to determine that) and the only potential use might be to test which form was submitted though I use the name attribute on the submit buttons instead.

Lastly use divisible elements for your form fields, not paragraphs. You may have only one or two fieldset elements (they should encompass all the (X)HTML elements in the form element) though if you're going to have a form and want to visually format label and input text elements put each pair (of label and input text elements) in to a divisible element. If they visually aren't creating a grid like layout (if it's what you desire) then make sure that the divisible elements clear via CSS (e.g. form div {clear: both;}).

- John

nyteshade

12:43 pm on Jun 12, 2011 (gmt 0)

10+ Year Member



Thank you JAB Creations. I'm grateful that you took the time, like others here, to detail such a generous reply. As luck would have it, I'm on my third PHP book, so your reference to PHP comes in handy. I'm just getting to XML schemas in Beginning XML 3rd edition and still digesting MIME (file?) types. I come here occasionally because I need answers from real people who have real world experience that books never seem to offer. For instance, your reference to divisible elements; I'm assuming you are referring to the div element and my use of p element to wrap my labels and input tags? From my reading I learned to not over-use divs and to not just put text or in-line tags in a document naked, the p element seemed to be the best choice, but I'll look into it. I'll be back once I tidy things up. Peace.

JAB Creations

4:20 am on Jun 13, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



True, there can be overkill with divisible elements though you'll still find it absolutely necessary to often nest a child divisible element inside of a parent divisible element because of how CSS layout works.

In regards to media types/mime here is what you need to know...

text/html - It works and you can get away with a lot though it's ultimately unreliable and will lead you to poor coding practices, avoid it whenever possible.

application/xhtml+xml - It works most of the time (except IE8 and older and Konqueror fails to declare support in it's header though it does technically support it). In my first post on this thread I posted code that will use this media type/mime whenever possible based off of support declared by headers. Be wary of IE7 (and some IE "modes") which declares supports for "*/*" which incorrectly suggests it supports all media types/mimes in ALL of existence.

text/xml - This is the media type/mime to use when importing XHTML as XML in to an XHTML application. Keep in mind you'll need to declare the XML namespace on the parent most element of that XML.

text/javascript - While JavaScript should be served as application/javascript if you're aiming for maximum compatibility you'll want to use this media type/mime instead.

In regards to the books you are correct. The best way to learn code is to start with a working example and minimize all the code around it until you can learn to replicate the functionality. Sooner or later you get used to it and your understanding evolves to include an increasing amount of understanding of how to code with the given language.

- John

rocknbil

5:58 pm on Jun 13, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There simply is no reason to use HTML and text/html.


I'm not going to argue with you, but there is no reason to use XHTML if your document doesn't use XHTML features, which most don't. As for clean coding, you can clean code in any doctype - I've seem more crap XHTML tag soup in my time than I can stomach, and most coders don't even know why they use it other than "it's the default document" or "someone told them is was the best thing." XHTML has a place, and it's not static HTML.

nyteshade

1:48 pm on Jun 14, 2011 (gmt 0)

10+ Year Member



I'm not going to argue with either of you, keep teaching and I'll try to keep up. I'm using the strict standard in my html files as preparation to writing xml applications and to get in the habit of writing xhtml compliant elements. Whenever I discover I've taken a mis-step then I go back and update my entire site page by page, which also helps me learn the new thing. But I get your point rocknbil. A year ago I couldn't even spell DOCTYPE; but I just kept reading and writing and taking my lumps.