Click to See Complete Forum and Search --> : trim problems


premzero
11-10-2003, 05:23 PM
I'm having funny problems with the trim function.
Here's my code.


<FORM METHOD="post" ACTION="somefile.htm" name="topForm" onsubmit="checkChoice();return false;">
<INPUT TYPE="TEXT" NAME="keywords" SIZE="20" MAXLENGTH="50" VALUE="">
<INPUT TYPE="button" VALUE="Search" onclick="checkChoice();">
</form>



The header script handling the form.


function checkChoice(){
if (trim(document.all.keywords.value) == ""){
alert('Please enter a search query.');
}
else {
document.all.topForm.submit();
return true;
}
}


It gives an error right when I click search and points to
the line with the search button where it's calling the
JS function (on click).

I remove trim.. it works like a charm.

Please help.

zachzach
11-10-2003, 05:31 PM
add this script at the top of your page:



<script language="JavaScript">
<!--
function trim(s) {
while (s.substring(0,1) == ' ') {
s = s.substring(1,s.length);
}
while (s.substring(s.length-1,s.length) == ' ') {
s = s.substring(0,s.length-1);
}
return s;
}
//-->
</script>

premzero
11-10-2003, 06:49 PM
Thanks!
Works great!

I thought trim was a built-in JS function... hmm...

pyro
11-10-2003, 10:33 PM
I personally would recommend something like this above the method that Zach posted:

<script type="text/javascript">
str = " test ";
String.prototype.trim = function() {
var trim = this.replace(/^\s+/, "");
trim = trim.replace(/\s+$/, "");
return trim;
}
alert (str.trim());
</script>

zachzach
11-11-2003, 04:11 PM
yea, cuz mine would only take off one space

your dissmissing all my posts(but your scripts are better so...lol)

pyro
11-11-2003, 04:26 PM
Originally posted by zachzach
yea, cuz mine would only take off one spaceNo it won't... ;)

If you only wanted to remove one space, you'd do it like this (change the + to a ?). Usually, though, when using a trim function, it would be desired to get rid of all preceding and following spaces.

<script type="text/javascript">
str = " test ";
String.prototype.trim = function() {
var trim = this.replace(/^\s?/, "");
trim = trim.replace(/\s?$/, "");
return trim;
}
alert (str.trim());
</script>Also, I'm not dismissing your posts. I simply posted a better way of doing what they asked for. There is no need to use a loop in this situation, so it is better to not use one.

premzero
11-11-2003, 04:44 PM
Well I got 2 answers to one question. Both work well.
Couldn't ask for more. So... thanks!