...

# .search HELP!!!!

FastCougar
04-22-2004, 08:50 PM
I need to search for the exact string entered into a text box to see if it's part of a list. The code below works, but if I enter "112100", it's not balking because this is part of "112100N","112100P", etc. I need to find an occurance of "112100" by itself and if it's not found, error out.

function ValidatePart() {
var validPart = "112100EU,112100N,112100p,112100R,112100US";
// Validate Part Number
for (i=1; i<=vTotal; i++) {
if (document.frmCalc['Part'+i].value == ''){
alert("You must enter a part number.");
document.frmCalc['Part'+i].focus();
return false;
break;
}else{
if (validPart.search(document.frmCalc['Part'+i].value) == -1){
document.frmCalc['Part'+i].focus();
document.frmCalc['Part'+i].select();
return false;
break;
}
}
}
}

What am I doing wrong?

Willy Duitt
04-22-2004, 10:52 PM
You are searching within a string to see if anywhere within the string your substring is present.

I would use an array and the match method to loop thru the array and check if a match is present, if not then do your alert and return false. Although, you could also do this with the string you are currently using, you would have to split the string at the commas to make an array. Therefore, starting with an array is easier to code and shorter. ;)

Below is an example, I did not use your multiple inputs and check if any of them were empty because quite frankly, I do not understand the theory. Do all of the inputs need to be filled out?

Anways here is the example:
<script type="text/javascript">
<!--//
function ValidatePart(){
var validPart = new Array("112100EU","112100N","112100p","112100R","112100US");
for(partCount=0; partCount<validPart.length; partCount++){
if(document.frmCalc['Part1'].value.match(validPart[partCount])){
return true;
}

else if(partCount == validPart.length-1){
document.frmCalc['Part1'].focus();
document.frmCalc['Part1'].select();
return false;
}
}
}
//-->
</script>