I have a hidden field and I add string to it, separated by semicolon. How I can I check the duplication when adding a new string?
I am doing as
function AddToHiddenField(source, hdnFieldId)
{
var srcList = document.getElementById(source);
var hdnFieldSubstring = document.getElementById(hdnFieldId);
var len = srcList.length;
hdnFieldSubstring.value = '';
for(var i = 0; i < len; i++)
{
if (srcList.options[i] != null)
{
if (hdnFieldSubstring.value == "")
{
hdnFieldSubstring.value = srcList.options[i].text;
}
else
{
hdnFieldSubstring.value = hdnFieldSubstring.value + ";" + srcList.options[i].text;
}
}
}
}
How can I check a string already exists in hdnFieldSubstring before added to it (in javascript)?
You can use JavaScript’sindexOf()method. If the return value is greater than ‘-1’, then it is in the string.Several commenters made a good point about
indexOf()returning false positives. I’ve updated my answer to correct that, and also include spelling fixes. I’m using thecontains()method from this question. Of course this will only work if yoursrcListdoesn’t contain semicolons.If I were you, I’d fix the spelling errors in your variable names. You’ll thank yourself later if you use the correct spelling for all variable names (unless you really mean to use “filed” instead of “field”)