• How to embed and read multiple values into one option in an HTML drop-down

    Posted on June 24, 2013 by in Technology, Varvia

    HTML drop-down lists let users pick a value from a list. Here is an example

    <select id="Cars">
      <option value="audi">Audi</option>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>

    Each <option> returns a single value, example if user picks option Audi, the value of the drop-down becomes “audi”. But, what if you would like to embed more information into each option value?

    One way to do this is by concatenating the additional value items into the Value string of the option, separating them using a delimiter, such as ‘^’ and ‘@’.  Here is an example where we embed :

     <option value="audi^emb_val_2_here@emb_val_3_here">Audi</option>

    Now when the user chooses option Audi, the drop-down value becomes the string “audi^emb_val_2_here@emb_val_3_here“.

    You can then parse out each value. For example, in Javascript you can obtain emb_val_2_here as following:

    // get the whole value string at selected option
    var s = document.getElementById("Cars").value;
    // in Javascript, first character in a string has index zero
    var value2 = s.substring(s.indexOf('^')+1, s.indexOf('@'));

    You can use same technique to extract parts of an options’s text. Example:

    <option value="audi">Audi-2012,Red</option>

    In Javascript, to get the 2012 value you can do this:

    var idx = document.getElementById("Cars").selectedIndex;
    var opt = document.getElementById("Cars").options;
    var line = opt[idx].text; // text of option at given selection
    var year = line.substring(line.indexOf('-')+1, line.indexOf(','));


One Responseso far.

  1. maillot psg says:

    maillot psg…

    I am quite enjoyed for this blog. Its an useful subject. It help me very much to solve some issues. Its prospect are so fantastic and functioning fashion so speedy. I consider it could be help all of you. Many thanks a lot for making the most of this e…