Making XHTML valid

Sorry a simple enough action but just cant get it valid, the following code works find but not valid because of the form name so change name to id and then what? here i am stuck. help please

function showName(){
var name = document.nameForm.name.value;
window.alert("Hello " + name + “welcome to my site”);
}

<h2>Display Name</h2>
<form name=“nameForm” action=“#”>
<p>Name: <input type=“text” name=“name” /><br /><br />
<input type=“submit” value=“Display” onclick=“showName();” /></p>
</form>

JavaScript isn’t XHTML and therefore needs to be either wrapped inside a <![CDATA]> tag or better yet put into a completely separate file.

You might also consider adding labels to your form so that people can tell which field is which (possibly not so important as you only have the one input but you don’t want to get into bad habits).

The onclick would be less obtrusive if you moved it into the JavaScript. Also referencing the HTML from JavaScript using ids instead of names is preferred as the names are there for the server side processing and can make the JavaScript extremely complex.

I assume that the debugging alert call is simply there to debug the code and will be replaced with something else prior to the page going live.

I now have my form like this

<form id=“nameForm” action=“#”>
<p>Name: <input type=“text” name=“name” /><br /><br />
<input type=“submit” value=“Display” onclick=“showName();” /></p>
</form>

but how do i make var name = nameForm now?

You can drop the onclick=“showName();” and do this:


<h2 id="notice"></h2>
<div id="displayName">
	<h2>Display Name</h2>
	<form name="nameForm" action="#">
		<label>Name: </label><input type="text" name="name" />
		<input type="submit" value="Display" />
	</form> 	
</div>
<script>
	var frm = document.nameForm;
		frm.onsubmit = function() {
			if( frm.name.value !== '' ) {
				var displayName = document.getElementById('displayName'),
					notice = document.getElementById('notice');
					
				displayName.style.display = 'none';
				notice.innerHTML = "Hello " + frm.name.value + ", and welcome to my site!"
			}
			return false;
		};
</script>

See how there isn’t any inline javascript now associated in the HTML?

The only problem with that is that the HTML is invalid because you need a <fieldset>, <div> or <p> wrapped around the content of the form inside the <form> tag because <input> is not allowed directly inside of <form> - it must be a grandchild element and not a child element.

felgall, forgot about that… for strict - then we need to remove the name attribute (or change it to an id) in the form. For transitional, this validates.

Yes but transitional means it is effectively HTML 3.2 and only working toward becoming HTML4/XHTML1