Carry additional information in the HTML select / option dropdown

I want to carry additional hidden information (for example, zip code) in the HTML select / drop-down list of options and make it available for the javascript function when selecting options for choosing custom changes.

This is what I would like to do (but it does not work).

<select id="sel_activity" onchange="selectionChange(this.info)"> 
    <option info=""       value="CAR">CAR PROBLEM</option> 
    <option info=""       value="COFFEE">Coffee Break</option>
    <option info="45678"  value="INV">INVENTORY COUNT</option>
    <option info="23567"  value="INVDROP">Inventory</option>
    <option info="" value="LUNCH">Lunch Break</option> 
    <option info="87654"  value="MEET">Meeting</option>
</select>

.
.
.

function selectionChange(info){      
    alert(info);
}
+5
source share
6 answers

HTML 5 provides data- * attributes, you can define your own attributes, just prefix them with data. Like data-info, data-zip or something else.

+5
source

I would use jQuery to get the attribute value using this function:

attr( attributeName )

something like that:

       $("select").change(function () {

          $("select option:selected").each(function () {
                var info = $(this).attr("info");
                alert(info);
              });

        })
        .trigger('change');

:

 attr( attributeName, value )

API

+5

onchange="selectionChange(this.options.item(this.selectedIndex).getAttribute('info'))"

+3

, .

, ...

<select id="sel_activity" onchange="selectionChange(this)">
  <option value="|CAR">CAR PROBLEM</option> 
  <option value="|COFFEE">Coffee Break</option>
  <option value="45678|INV">INVENTORY COUNT</option>
  <option value="23567|INVDROP">Inventory</option>
  <option value="|LUNCH">Lunch Break</option> 
  <option value="87654|MEET">Meeting</option>
</select>

JavaScript...

 function selectionChange(o) {
   // an alternative ...    
   var values = o.options[o.options.selectedIndex].value.split("|");            
   alert("Selected Index? "+(o.options.selectedIndex+1)
    +"\nInfo? "+values[0]
    +"\nValue? "+values[1]);
   values = null;
  }
+2

- , , , .

- , , .

0

classand idare good attributes for such information storage. One thing to keep in mind is that by W3C standards idit cannot start with a number, so if you were hoping to keep the numbers as additional information, you would have to either use classor implement some kind of additional Javascript that pulls the number from idas a function substr.

-1
source

All Articles