Ive got a really strange problem with some javascript code that ive written. I have set this code to execute on load. The idea of it is to remove a value from a text field if it is listed in another field. Here is the code:
var diseases = document.getElementById("AffectedBy").value;
var diseasearray = diseases.split("-");
alert("disease array size: " + diseasearray.length);
for (i=0;i<diseasearray.length;i++)
if (diseases.match("-" + diseasearray[i]))
{
diseasearray[i] = "-" + diseasearray[i];
alert(diseasearray[i]);
document.getElementById("DiseaseNotSelected").value=document.getElementById("DiseaseNotSelected").value.replace(diseasearray[i],"")
}
This code above gives an array size of 3 (1 blank, and 2 values) but when I display the values in the alert it only shows 2 values(1 blank, and 1 value)
This piece of code:
var foods = document.getElementById("FoodFor").value;
var foodarray = foods.split("-");
alert("food array size: " + foodarray.length);
for (i=0;i<foodarray.length;i++)
if (foods.match("-" + foodarray[i]))
{
foodarray[i] = "-" + foodarray[i];
alert(foodarray[i]);
document.getElementById("FoodNotSelected").value=document.getElementById("FoodNotSelected").value.replace(foodarray[i],"")
}
This code above gives an array size of 3 (1 blank, and 2 values) and when I display the values in the alert it only shows 3 values(1 blank, and 2 value).
Can anyone see a reason why the first code block only shows 2 items in the array as I cant see why and its really bugging me now.
As I said in my comment above: beware that whatever you pass into match will get turned into a regular expression. If that contains some special character, it might not match where you would expect it to (or vice versa).
The string
White Spot (Ich)will be turned into the regex/White Spot (Ich)/; which does not matchWhite Spot (Ich)but does matchWhite Spot Ich, since the parentheses are grouping operators in a regex.Change the regular expression test
into the plain string comparison
and you should be set.
(I think. 🙂