Solved

troubleshooting a function

Posted on 2009-05-15
11
242 Views
Last Modified: 2012-05-07
Hi, experts
I'm trying to get a function work that will grab numerical ranges from a text box and replace it with the numerical sequence involved (e.g., replacie "20-25" with "20,21,23,24,25").

My function works (UtilsGiveNumsInRange) fine when I hard code the numbers involved, but when I use the same value pulled from the text box, it works but then adds a bunch of digits afterwards. As far as I can tell, the number being pulled from the textbox via UtilsGetFinalNumberInRange() is identical to the hardcoded that works, so I'm stumped. (Also, this error only affects the 2nd number in the pair. When I use the function for the 1st number there is no problem.)

Do I need to be doing some casting?

Thanks.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
 
<script language="JavaScript">
<!-- 
// **** BEGIN UTILITY FUNCTIONS ****
 
var something;
var strRangeSeparator = "-";
 
function UtilsStringHasOnlyPermittedChars(strWhole, strPermittedChars) //WORKS
{
// Returns -1 if strWhole contains anything not in strPermitted
	var temp;
	for (var i=0;i<strWhole.length;i++)
		{	temp=strWhole.substring(i,i+1)
			if (strPermittedChars.indexOf(temp)==-1){return false} 	}
	return true;
}
 
function UtilsStringContainsDelimiter(strWhole, strDelimiter) //WORKS
{
	if (InStr(strWhole,strDelimiter)==-1) 	{ 		return false; 	}
	return true;
}
 
function UtilsGetInitialNumberInRange(strRange,strRangeSeparator) //WORKS
{	return strRange.substring(0,parseInt(strRange.indexOf(strRangeSeparator)));	}
 
function UtilsGetFinalNumberInRange(strRange,strRangeSeparator) //WORKS
{	return strRange.substring(strRange.indexOf(strRangeSeparator)+1,strRange.length); }
 
 
function UtilsGiveNumsInRange(strInitNum, strFinalNum,strDelimiter) //WORKS
{ 
	temp="";
	for (var i =strInitNum; i<strFinalNum+1; i++)
	{
		temp = temp + i;
		if(i<strFinalNum){ temp = temp + strDelimiter}//This handles the final number (which shouldn't be followed by a delimiter)
	}
	return temp;
}
 
 
function TestIt()
{
 
	var strPermittedChars = "1234567890-";
	var something = document.f1.t1.value;
	var numBeginYear;
	var numEndYear;
 
	
	//TEST 01
	
		alert("It works with hardcoded vals: " + UtilsGiveNumsInRange(
		25,
		51,
		","
		));
		
	alert("No trailing spaces, either. |" + UtilsGetFinalNumberInRange(something,"-") + "|");
 
	alert("It works for the 1st number." + UtilsGiveNumsInRange(
			UtilsGetInitialNumberInRange(something,"-"),
			25,
			"-"
		));	
	alert(UtilsGiveNumsInRange(
			UtilsGetInitialNumberInRange(something,"-"),
			UtilsGetFinalNumberInRange(something,"-"),
			"-"
		));
 
	if (UtilsStringHasOnlyPermittedChars(something,strPermittedChars)==true)
	{
	}
	
 
	
	if (InStr(something,strRangeSeparator)==1)
	{
		// There's only one year.
	}
	else
	{
 
	
	}
	
/*	for (var i=0;i<InStr(something,strRangeSeparator); i++
	{
	
	
	}*/
	
	
	//alert(document.f1.t1.value.length);
	
	
}
function InStr(strSearch, charSearchFor)
{
	// Requires a Mid() function.
	for (i=0; i < strSearch.length; i++)
		{ if (charSearchFor == Mid(strSearch, i, 1)) {  return i; }  }
	return -1;
}
 
function Mid(str, start, len)
{  // Make sure start and len are within proper bounds
    if (start < 0 || len < 0) return "";
    var iEnd, iLen = String(str).length;
    if (start + len > iLen)
          iEnd = iLen;
    else
          iEnd = start + len;
    return String(str).substring(start,iEnd);
}
// ***** END UTILITY FUNCTIONS ******
-->
</script>
</head>
 
<body>
<p>Header</p>
<p>kljkljl </p>
<p>
        <FORM NAME = f1>
          <CENTER>
            <INPUT TYPE = text NAME = t1 SIZE = 15 VALUE ="25-51">
            <INPUT TYPE = Button VALUE = "Go" onClick = TestIt()>
          </CENTER>
        </FORM>
</p>
</body>
</html>

Open in new window

jserror.doc
0
Comment
Question by:Leprechaun
  • 8
  • 3
11 Comments
 

Author Comment

by:Leprechaun
ID: 24395368
Sorry, that version of the page is pretty disorganized. Here's a slightly neater version.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
 
<script language="JavaScript">
<!-- 
// **** BEGIN UTILITY FUNCTIONS ****
function UtilsStringHasOnlyPermittedChars(strWhole, strPermittedChars) //WORKS
{
// Returns -1 if strWhole contains anything not in strPermitted
	var temp;
	for (var i=0;i<strWhole.length;i++)
		{	temp=strWhole.substring(i,i+1)
			if (strPermittedChars.indexOf(temp)==-1){return false} 	}
	return true;
}
function UtilsStringContainsDelimiter(strWhole, strDelimiter) //WORKS
{
	if (InStr(strWhole,strDelimiter)==-1) 	{ 		return false; 	}
	return true;
}
function UtilsGetInitialNumberInRange(strRange,strRangeSeparator) //WORKS
{	return strRange.substring(0,parseInt(strRange.indexOf(strRangeSeparator)));	}
 
function UtilsGetFinalNumberInRange(strRange,strRangeSeparator) //WORKS
{	return strRange.substring(strRange.indexOf(strRangeSeparator)+1,strRange.length); }
 
/*function UtilsGetNumsFromDelimitedList(strList,strDelimiter)
{
	temp = "";
	for (var i=0; i<InStr(strList,strDelimiter); i++)
	{	
	}	
}*/
 
function UtilsGiveNumsInRange(strInitNum, strFinalNum,strDelimiter) //WORKS
{ 
	temp="";
	for (var i =strInitNum; i<strFinalNum+1; i++)
	{
		temp = temp + i;
		if(i<strFinalNum){ temp = temp + strDelimiter}//This handles the final number (which shouldn't be followed by a delimiter)
	}
	return temp;
}
function InStr(strSearch, charSearchFor)
{
	// Requires a Mid() function.
	for (i=0; i < strSearch.length; i++)
		{ if (charSearchFor == Mid(strSearch, i, 1)) {  return i; }  }
	return -1;
}
function Mid(str, start, len)
{  // Make sure start and len are within proper bounds
    if (start < 0 || len < 0) return "";
    var iEnd, iLen = String(str).length;
    if (start + len > iLen)
          iEnd = iLen;
    else
          iEnd = start + len;
    return String(str).substring(start,iEnd);
}
// ***** END UTILITY FUNCTIONS ******
 
var something;
var strRangeSeparator = "-";
 
function TestIt()
{
 
	var strPermittedChars = "1234567890-";
	var something = document.f1.t1.value;
	var numBeginYear;
	var numEndYear;
 
	
	//TEST 01
	
		alert("It works with hardcoded vals: " + UtilsGiveNumsInRange(
		20,
		25,
		","
		));
		
	//alert("|" + UtilsGetFinalNumberInRange(something,"-") + "|");
	
	alert("But it doesn't work when the numbers are pulled from the textbox." + UtilsGiveNumsInRange(
			UtilsGetInitialNumberInRange(something,"-"),
			UtilsGetFinalNumberInRange(something,"-"),
			","
		));
 
	alert("It works for the 1st number." + UtilsGiveNumsInRange(
			UtilsGetInitialNumberInRange(something,"-"),
			25,
			","
		));		
}
 
-->
</script>
</head>
 
<body>
<p>Header</p>
<p>kljkljl </p>
<p>
        <FORM NAME = f1>
          <CENTER>
            <INPUT TYPE = text NAME = t1 SIZE = 15 VALUE ="20-25">
            <INPUT TYPE = Button VALUE = "Go" onClick = TestIt()>
          </CENTER>
        </FORM>
</p>
</body>
</html>

Open in new window

0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 50 total points
ID: 24401491
If strFinalNum is a string (and it is from a form field), your current code adds a 1 to the string
So if it was 25, you get 251

function UtilsGiveNumsInRange(strInitNum, strFinalNum, strDelimiter) {
  var temp="";
  for (var i=parseInt(strInitNum,10),n=parseInt(strFinalNum,10); i<=n; i++) temp += strDelimiter+i;
  return (temp)?temp.substring(1):"";
}

Open in new window

0
 

Author Comment

by:Leprechaun
ID: 24411849
Dagnabit! That explains it. Thank you.
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 

Author Comment

by:Leprechaun
ID: 24412132
Thanks for cleaning up my code.  That's a lot more elegant. :)

I guess the "i++" in optional in a for loop in JavaScript?

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 24412279
Hmm erm... Not really
You can do
for (;something;)
and add yourself inside the loop, however the i++ is there:

for (var i=parseInt(strInitNum,10),n=parseInt(strFinalNum,10); i<=n; i++)

I just do TWO assignment in the first part (separated by comma):

for (
var i=parseInt(strInitNum,10), n=parseInt(strFinalNum,10);
i<=n;
i++)
0
 

Author Comment

by:Leprechaun
ID: 24412408
Oh, duh. I see that "i++" was there after all. Sorry, didn't notice it was off-screen.
0
 

Author Comment

by:Leprechaun
ID: 24412816
This is great, but I'm going to have to ask a dumb question:

Why isn't the output of this ",20,21,22,23,24,25" ? On the first pass, shouldn't temp be set to "," on the first loop and from then on get the delmiter and number appended?

0
 

Author Comment

by:Leprechaun
ID: 24414338
Sorry for the silly question about the i++. I had overlooked that bit because it was off screen in the code window. I thought you'd left it out and was wondering if perhaps that loop defaulted to that when no increment value is provided (which would presumably save a bit of coding in a lot of cases). Of course, as soon as I hit SUBMIT I looked back at the code and saw that you'd included the i++ as one would expect. Duh. I don't read too good sometimes!


0
 

Author Comment

by:Leprechaun
ID: 24414411
Oh, I get it. The substring bit is clipping off the leading comma. That's a nice way to handle it.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 24418301
Hehe, me being in CET made you answer all your questions yourself. Well done :)
0
 

Author Comment

by:Leprechaun
ID: 24424373
Tx. Haven't dealt with JS in a long time, so it's all a bit unfamiliar.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

The following is a collection of cases for strange behaviour when using advanced techniques in DOS batch files. You should have some basic experience in batch "programming", as I'm assuming some knowledge and not further explain the basics. For some…
In this tutorial I will show you how to provide a dynamic RTF document on your website generated with data from your database. For this tutorial you will need Microsoft Word or WordPad, WhizBase and Microsoft Access. In this tutorial I will show …
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
The viewer will learn how to count occurrences of each item in an array.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question