Tutorial :Check contents of a hidden field in javascript



Question:

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)?


Solution:1

You can use JavaScript's indexOf() 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 the contains() method from this question. Of course this will only work if your srcList doesn't contain semicolons.

function contains(arr, obj) {    var i = arr.length;    while (i--) {      if (arr[i] === obj) {        return true;      }    }    return false;  }    function AddToHiddenField(source, hdnFieldId)  {      var srcList = document.getElementById(source);      var hdnFieldSubstring = document.getElementById(hdnFieldId);      var len = srcList.length;      var value = '';      for(var i = 0; i < len; i++)       {          var currentOption = srcList.options[i].text;          if (srcList.options[i] != null)           {              if (value  == "")              {                  value  = currentOption;              }              else if(!contains(val.split(';'), currentOption))              {                  value += ";" + currentOption;              }                              }      }      hdnFieldSubstring.value = value;  }  

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")


Solution:2

This would be simpler if you always put the semi colon in the value. I.e.

if (srcList.options[i] && hdnFieldSubstring.value.indexOf(srcList.options[i].text + ";") == -1)      hdnFieldSubstring.value += srcList.options[i].text + ";";  

Now you can always search for the string with a semi-colon on the end.

  • Don't forget to make sure that the strings don't include semi-colons already.
  • If the last semi-colon will cause you problems then strip it off just before submitting the form by putting a handler on the submit button.


Solution:3

Honestly I wouldn't persist the data in the field, I'd do it in an array.

function AddToHiddenField(source, hdnFieldId)  {      //create storage if it doesn't exist      if (typeof(window.hiddenFieldData)=='undefined')      {        window.hiddenFieldData = [];      }        var srcList = document.getElementById(source);      for(var i=0, n=srcList.length, value; i<n; i++)      {        if (srcList.options[i] != null)         {          var value = srcList.options[i].text;          /*           ignores duplicates by virtue of overwriting index -           if you didn't want to just overwrite you'd wrap this with:            if(typeof(window.hiddenFieldData[value])=='undefined')                   */          window.hiddenFieldData[value] = value;        }      }        //serialise storage to hidden field      document.getElementById(hdnFieldId).value = window.hiddenFieldData.join(';');  }  

Rule of thumb: if you have to deserialise a string to maintain integrity, you shouldn't be using a string as data storage.

note: if your original source was in a hidden field for some reason, I'd still do it like this but I'd init my array with a string.split


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »