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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with finding Javascript Sample

Status
Not open for further replies.

dcroe05

Programmer
Feb 15, 2005
44
US
While I am a programmer I am not a javascript programmer. I'm looking for a script I can alter for my purposes.

Right now I have several javascripts that simply return a text string. They're all basically the same information but each script returns the info in a slightly different format (one script returns basic info for a sidebar, one returns longer info for a page)

What I'd like is a script that can be called with a variable, and the script uses that variable to determine what text gets returned.

Is this even possible?
 
Sure it is - there are several ways of doing this, such as:

Code:
function doSomething(someVar) {
   if (someVar == 'abc' || someVar == 'jkl') {
      return('def');
   } else if (someVar == 'ghi') {
      return('xyz');
   } else {
      return('123');
   }
}

Or you could use a switch statement:

Code:
function doSomething(someVar) {
   var retVal = '';
   switch (someVar) {
      case 'abc':
      case 'jkl':
         retVal = 'def';
         break;
      case 'ghi':
         retVal = 'xyz';
         break;
      default:
         retVal = '123';
         break;
   }
   return(retVal);
}

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Yes and no...

I discovered that if I call two consecutive scripts that variable values carry over from the first to the second, so I used one script to set a variable and the second to return the text based on the variable.

Thank you.
 
Code:
<html>
<head>

<script type="text/javascript">
function myfunction(txt, foo)
{
switch (foo)
{
case 1:
  alert(txt);
  break
case 2:
  alert(txt.substring(0,10)+"...");
  break
default:
  alert("Sorry, the item could not be found");
}
}
</script>

</head>
<body>

<form>
<input type="button" 
onclick="myfunction('Hello, this is a string which is very long', 1)"
value="Get full text">
<input type="button" 
onclick="myfunction('Hello, this is a string which is very long', 2)"
value="Get short text">
<input type="button" 
onclick="myfunction()"
value="Get default text">
</form>

<p>By pressing the button, a function with an argument will be called. The function will alert
this argument.</p>

</body>
</html>

Olav Alexander Mjelde
Admin & Webmaster
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top