Jump to content

Best way to get input values? (parameters or directly)


VelvetMirror

Recommended Posts

In most of my scripts I usually have to get the input's value, so I was wondering which one is the best programming practice (or most used) to get them:1. Directly:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">	<head>		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />		<title></title>		<script type="text/javascript">			function getValue()			{				test=document.getElementById("test").value;				alert(test);			}		</script>	</head>	<body>		<form action="">			<fieldset>				<input id="test" type="text" />				<input type="button" value="get value" onclick="getValue()" />			</fieldset>		</form>	</body></html>

2. By parameter:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">	<head>		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />		<title></title>		<script type="text/javascript">			function getValue(id)			{				test=document.getElementById(id).value;				alert(test);			}		</script>	</head>	<body>		<form action="">			<fieldset>				<input id="test" type="text" />				<input type="button" value="get value" onclick="getValue('test')" />			</fieldset>		</form>	</body></html>

Link to comment
Share on other sites

Well, by passing the id as a parameter (as opposed to hard-coding it) you make your script more flexible, and that's good.

Link to comment
Share on other sites

Well, by passing the id as a parameter (as opposed to hard-coding it) you make your script more flexible, and that's good.
Right. And you can shorten it a little more if you pass in the element:
function getValue(el) {	alert(el.value);}....<input type="button" value="get value" onclick="getValue(this)" />

This only shrinks it by one line, so on longer functions it doesn't make much difference. But this way makes it even a little bit more flexible too, because it doesn't require that your input has an id.EDIT:Ah, I realized that you are getting the value of a different element, not the one that was clicked. This method however, is still useful if you need to pass whichever element was clicked (or any other event) to the function. For example, say you wanted to validate an input when its value was changed.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...