Combining Input Fields
Question: Can I save space in my form by getting more than one input value from just one text field?
Answer:
Yes. For example, you can display a text input field and a select box.
Using the select box, the user will be able to choose which kind of value
to input in the text field. All input data can actually be submitted to the server
in additional hidden form elements.
Try this example:
This form was created using the following JavaScript code:
<form name=form1 action="" onSubmit="return validate()">
<input name="name" type=hidden value="">
<input name="email" type=hidden value="">
<input name="country" type=hidden value="">
<select name=s1 onChange="refill()">
<option value="name" selected >Your name:
<option value="email" >Your email address:
<option value="country" >Your country:
</select>
<input name=t1 type=text value="" size=20>
<input name=b1 type=submit value="Enter!">
</form>
<script language="JavaScript">
<!--
isFilled=new Array(0,0,0);
oldActiveField="name"; oldIndex=0;
theActiveField="name"; theIndex=0;
theValue='';
theForm=document.form1;
function refill() {
oldIndex=theIndex;
theIndex=theForm.s1.selectedIndex;
oldActiveField=theActiveField;
theActiveField=theForm.s1.options[theIndex].value;
theValue=theForm.t1.value;
eval('theForm.'+oldActiveField+'.value=theValue');
eval('theForm.t1.value=theForm.'+theActiveField+'.value');
if (theValue!='') isFilled[oldIndex]=1;
if (theValue=='') isFilled[oldIndex]=0;
}
function read() {
oldIndex=theForm.s1.selectedIndex;
oldActiveField=theForm.s1.options[oldIndex].value;
theValue=theForm.t1.value;
eval('theForm.'+oldActiveField+'.value=theValue');
if (theValue!='') isFilled[theIndex]=1;
if (theValue=='') isFilled[theIndex]=0;
}
function validate() {
read();
for (var k=0; k<isFilled.length; k++) {
if (!isFilled[k]) {
theIndex=k;
theForm.s1.selectedIndex=k;
theForm.t1.value='';
theActiveField=theForm.s1.options[k].value;
if (oldIndex==k) alert ('Please fill in your '+theActiveField)
return false;
}
}
alert ('You are submitting the following data:'
+'\nName: '+theForm.name.value
+'\nEmail: '+theForm.email.value
+'\nCountry: '+theForm.country.value
)
return false;
// Instead of returning false in all cases,
// a real-life code here would validate the data
// and return true if the user submitted valid data
}
//-->
</script>
JavaScripter.net.
Copyright
© 1999-2006, Alexei Kourbatov