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!

how to pass a variable to a script 1

Status
Not open for further replies.

carruba

Technical User
Jun 2, 2003
2
US
I want to reuse a script; for that I need to pass the input field name to the script. I added the '+' but it does not work. The script and form would look something like this:

<script>
function checkLength(fieldName){
if (document.myForm.+fieldName+.value.length > 400){
alert(&quot;Your text is too long, it has been truncated.&quot;)
document.myForm.+fieldName+.value = document.myForm.+fieldName+.value.substr(0,400)
}
}
</script>

<form name=&quot;myForm&quot;>
<textarea name=&quot;A2a&quot; cols=&quot;95&quot; rows=&quot;3&quot; tabindex=&quot;13&quot; wrap=&quot;soft&quot; onBlur=&quot;checkLength(A2a)&quot;>
 
Try it more like this:

Code:
<script>
function checkLength(theField){
  if (theField.value.length > 400){
    alert(&quot;Your text is too long, it has been truncated.&quot;)
    theField.value = theField.value.substr(0,400)
  }
}
</script>

<form name=&quot;myForm&quot;>
<textarea name=&quot;A2a&quot; cols=&quot;95&quot; rows=&quot;3&quot; tabindex=&quot;13&quot; wrap=&quot;soft&quot; onBlur=&quot;checkLength(this)&quot;>

The 'this' in [tt]onBlur=&quot;checkLength(this)&quot;[/tt] makes use of JavaScript's object-oriented nature and passes a reference to the current object (namely your textarea field) This means that you no longer have to go the long way around to access the field, you can simply access the reference as passed to your function as an argument.

Also, now if you want to re-use the function on another page or another site, you don't have to edit the form name inside the function.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top