Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Clear blank spaces and tabs in form inputs 1

Status
Not open for further replies.

evergrean100

Technical User
Dec 1, 2006
115
US
I would like to create a JavaScript to clear any blank tab space entries made on a form submit.

If someone enters tabs or blank spaces in the form inputs then clear it out with JavaScript.

My attempt below is not clearing the tabs or blank spaces and doesnt seem to call my function.
Please advise.

Code:
<script>
function eliminateSpace()
{
if(fieldOne == "" || fieldTwo == "" || fieldThree == "")
{
return fieldOne.replace(/^\s+|\s+$/g, '');
return fieldTwo.replace(/^\s+|\s+$/g, '');
return fieldThree.replace(/^\s+|\s+$/g, '');
}
}
</script>

....
<form method="get" name="myform" action="thepage.jsp" onsubmit="eliminateSpace()">
<input type="text" name="fieldOne">
<input type="text" name="fieldTwo">
<input type="text" name="fieldThree">
<input type="submit" name="submit">
</form>
 
Hi

The [tt]fieldOne[/tt] is a [tt]Text[/tt] object which does not have [tt]replace()[/tt] method. Anyway, you can not reference fields like that. And the [tt]replace()[/tt] method does not substitute the original value. And use less [tt]return[/tt] statements.
Code:
function eliminateSpace()
{
  if ([red]document.myform.[/red]fieldOne[red].value[/red] == "" || [red]document.myform.[/red]fieldTwo[red].value[/red] == "" || [red]document.myform.[/red]fieldThree[red].value[/red] == "")
  {
    [red]document.myform.fieldOne.value=[/red][red]document.myform.[/red]fieldOne.[red]value.[/red]replace(/^\s+|\s+$/g, '');
    [red]document.myform.fieldTwo.value=[/red][red]document.myform.[/red]fieldTwo.[red]value.[/red]replace(/^\s+|\s+$/g, '');
    [red]document.myform.fieldThree.value=[/red][red]document.myform.[/red]fieldThree.[red]value.[/red]replace(/^\s+|\s+$/g, '');
  }
}
And indent your code.

Anyway, that [tt]if[/tt] statement there looks bad. An useless.

Personally I would prefer somethink generic like this :
Code:
<script>
[red]function eliminateSpace(where)
{
  el=where.elements.length;
  for (i=0;i<el;i++)
    if (where.elements[i].type=='text' || where.elements[i].type=='textarea')
      if (where.elements[i].value!='')
        where.elements[i].value=where.elements[i].value.replace(/^\s+|\s+$/g, '');
}[/red]
</script>

....
<form method="get" name="myform" action="thepage.jsp" onsubmit="eliminateSpace([red]this[/red])">
<input type="text" name="fieldOne">
<input type="text" name="fieldTwo">
<input type="text" name="fieldThree">
<input type="submit" name="submit">
</form>

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top