131

I got a select tag with some options in a HTML form:
(the data will be collected and processed using PHP)

Testing:

<select name="Testing">  
  <option value="1"> One  
  <option value="2"> Two  
  <option value="3"> Three
</select>

Is it possible for an option to carry multiple values like when a user selects "One", then a few other values related to this option will be written to the Database.

How should I design the select Tag so that each of the options can carry one than one value like this:

<select name="Testing">  
  <option value="1" value="2010"> One  
  <option value="2" value="2122"> Two  
  <option value="3" value="0"> Three
</select>
Jonathan Callen
  • 11,301
  • 2
  • 23
  • 44
user327712
  • 3,291
  • 4
  • 37
  • 45

18 Answers18

189

One way to do this, first one an array, 2nd an object:

    <select name="">
        <option value='{"num_sequence":[0,1,2,3]}'>Option one</option>
        <option value='{"foo":"bar","one":"two"}'>Option two</option>
    </select>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Robusto
  • 31,447
  • 8
  • 56
  • 77
  • 10
    +1 for elegant solution. N.B. If you use option two, then I recommend you use $.parseJSON($(this).val()) in the change event to get a javascript object, assuming you need to get at each value separately. – Lucas B Jul 25 '12 at 21:29
  • 2
    -1 because this answer induces the OP to have a big security problem in his code while evaluating the input. The best way to avoid this is using JSON, as suggested by @DavidHoerster, because the input is better behaved. – fotanus Aug 27 '13 at 19:10
  • 6
    @fotanus: My second example *is* a JSON object literal no different from what the other question proposes. As for the array, it's just an example. It's the responsibility of the server-side code to sanitize input values anyway. – Robusto Aug 27 '13 at 19:43
  • 1
    @Robusto the second example isn't a valid JSON. It is, in other hand, a ruby hash. My problem with your answer is not about what you explain or know (because I believe you know how to make this safe), it is about what it omits and could confuse a newbie developer (as it did with one friend of mine). – fotanus Aug 27 '13 at 19:50
  • @fotanus: Although it feels like scope creep to me, I've edited the answer to forestall objections that it doesn't lead people like your friend along securely enough. – Robusto Aug 27 '13 at 20:12
  • 1
    Sorry but I just don't get this working. what's wrong here: http://jsfiddle.net/XsfsK/1/ There must be something I'm not understanding right. – Markus Jun 25 '14 at 09:14
  • @Markus: Use `JSON.stringify` to format objects for inclusion as values, and `JSON.parse()` to recover them from the value attribute. – Robusto Jun 25 '14 at 10:12
  • @Robusto but the JSON isn't well-formed when trying to parse it with single quotes. – Markus Jun 25 '14 at 13:22
  • @Markus: Then substitute `\"` for the single quotes. – Robusto Jul 06 '14 at 11:59
  • This solution doesn't work @Markus proved it.... make this post more complete like the example of Markus – mejiamanuel57 Oct 10 '15 at 19:31
  • 11
    Good solution, but for the string to be parsed to JSON, the property names got to have double quotes, like so: value='{"foo":"bar","one":"two"}' – Lars-Lasse May 31 '17 at 21:48
  • 1
    Note that this solution is incorrect and fails to parse because single quotes is not valid JSON. – Zak Dec 13 '17 at 17:28
  • this answer works, but if you use multiple it won't. To work with multiple you will have to get the values, iterate through them and use `$.parseJSON(value)` and push them to a data array `var data = []; $.each(values, function (index, value) { data.push($.parseJSON(value)); })` – Jackal Sep 05 '19 at 08:28
  • for javascript don't forget to do JSON.parse(valueYOuGot) – Zeyad Shaban Dec 05 '20 at 10:47
63

I achieved it by using the PHP explode function, like this:

HTML Form (in a file I named 'doublevalue.php':

    <form name="car_form" method="post" action="doublevalue_action.php">
            <select name="car" id="car">
                    <option value="">Select Car</option>
                    <option value="BMW|Red">Red BMW</option>
                    <option value="Mercedes|Black">Black Mercedes</option>
            </select>
            <input type="submit" name="submit" id="submit" value="submit">
    </form>

PHP action (in a file I named doublevalue_action.php)

    <?php
            $result = $_POST['car'];
            $result_explode = explode('|', $result);
            echo "Model: ". $result_explode[0]."<br />";
            echo "Colour: ". $result_explode[1]."<br />";
    ?>

As you can see in the first piece of code, we're creating a standard HTML select box, with 2 options. Each option has 1 value, which has a separator (in this instance, '|') to split the values (in this case, model, and colour).

On the action page, I'm exploding the results into an array, then calling each one. As you can see, I've separated, and labelled them so you can see the effect this is causing.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Nedra
  • 631
  • 5
  • 2
  • 1
    I find this method very simple and very helpful, but I'm wondering is this method supported by all browsers? – Waiyl Karim Aug 08 '14 at 01:04
  • 4
    @WaiylKarim No reason why it should not work by all browsers. Browsers should not care about what is in the value.. And if they have problem with some symbols in it, there is no problem to choose another one. Like dot or # or _ or any character which can be used as delimiter on server side – Risinek Dec 03 '16 at 23:45
  • @Nedra any idea how to retrieve and edit this type of dropdown value from the database?I used this method to save in databse but when its in edit option the value in the dropdown is not working.using js,jquery – coder_000_ Feb 10 '22 at 07:36
40

its possible to have multiple values in a select option as shown below.

<select id="ddlEmployee" class="form-control">
    <option value="">-- Select --</option>
    <option value="1" data-city="Washington" data-doj="20-06-2011">John</option>
    <option value="2" data-city="California" data-doj="10-05-2015">Clif</option>
    <option value="3" data-city="Delhi" data-doj="01-01-2008">Alexander</option>
</select>

you can get selected value on change event using jquery as shown below.

$("#ddlEmployee").change(function () {
     alert($(this).find(':selected').data('city'));
});

You can find more details in this LINK

Vara
  • 755
  • 6
  • 13
16

When I need to do this, I make the other values data-values and then use js to assign them to a hidden input

<select id=select>
<option value=1 data-othervalue=2 data-someothervalue=3>
//...
</select>

<input type=hidden name=otherValue id=otherValue />
<input type=hidden name=someOtherValue id=someOtherValue />

<script>
$('#select').change(function () {
var otherValue=$(this).find('option:selected').attr('data-othervalue');
var someOtherValue=$(this).find('option:selected').attr('data-someothervalue');
$('#otherValue').val(otherValue);
$('#someOtherValue').val(someOtherValue);
});
</script>
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
  • 1
    This got me part of the way -- also, can use .data() to get them back out if you already have an element (vs doing a selector query). e.g. myElem.data('othervalue') – jsh Jan 27 '17 at 18:14
  • 2
    This isn't technically what OP asks, but it is 100% what I was trying to accomplish when I came searching here. +1 for the simple, better path to what I assume was the end goal of simply storing two pieces of data in a select option. – Lime Jul 07 '17 at 20:09
16

one option is to put multi value with comma seperated

like

value ="123,1234"

and in the server side separate them

Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
10

What about html data attributes? That's the easiest way. Reference from w3school

In your case

$('select').on('change', function() {
  alert('value a is:' + $("select option:selected").data('valuea') +
    '\nvalue b is:' + $("select option:selected").data('valueb')
  )
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<select name="Testing">
  <option value="1" data-valuea="2010" data-valueb="2011"> One
    <option value="2" data-valuea="2122" data-valueb="2123"> Two
      <option value="3" data-valuea="0" data-valueb="1"> Three
</select>
Ankit
  • 1,094
  • 11
  • 23
7

In HTML:

<SELECT NAME="Testing" id="Testing">  
  <OPTION VALUE="1,2010"> One  
  <OPTION VALUE="2,2122"> Two  
  <OPTION VALUE="3,0"> Three
</SELECT>

For JS:

  var valueOne= $('#Testing').val().split(',')[0];
  var valueTwo =$('#Testing').val().split(',')[1];
  console.log(valueOne); //output 1
  console.log(valueTwo); //output 2010
      

For PHP:

  $selectedValue= explode(',', $value);
  $valueOne= $exploded_value[0]; //output 1
  $valueTwo= $exploded_value[1]; //output 2010
desertnaut
  • 57,590
  • 26
  • 140
  • 166
kunal shaktawat
  • 1,428
  • 12
  • 21
5

If you're goal is to write this information to the database, then why do you need to have a primary value and 'related' values in the value attribute? Why not just send the primary value to the database and let the relational nature of the database take care of the rest.

If you need to have multiple values in your OPTIONs, try a delimiter that isn't very common:

<OPTION VALUE="1|2010">One</OPTION>

or add an object literal (JSON format):

<OPTION VALUE="{'primary':'1','secondary':'2010'}">One</OPTION>

It really depends on what you're trying to do.

Dharman
  • 30,962
  • 25
  • 85
  • 135
David Hoerster
  • 28,421
  • 8
  • 67
  • 102
5

I did this by using data attributes. Is a lot cleaner than other methods attempting to explode etc.

HTML

<select class="example">
    <option value="1" data-value="A">One</option>
    <option value="2" data-value="B">Two</option>
    <option value="3" data-value="C">Three</option>
    <option value="4" data-value="D">Four</option>
</select>

JS

$('select.example').change(function() {

    var other_val = $('select.example option[value="' + $(this).val() + '"]').data('value');

    console.log(other_val);

});
Jack
  • 3,271
  • 11
  • 48
  • 57
4

Put values for each option like

<SELECT NAME="val">
   <OPTION value="1:2:3:4"> 1-4  
   <OPTION value="5:6:7:8"> 5-8  
   <OPTION value="9:10:11:12"> 9-12
</SELECT>

At server side in case of PHP, use functions like explode [array] = explode([delimeter],[posted value]);

$values = explode(':',$_POST['val']

The above code returns an array that has only the numbers and the ':' get removed

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jaison Justus
  • 2,753
  • 8
  • 47
  • 65
4

Simplest way to do this:

<select name="demo_select">
    <option value='{"key1":"111","key2":"222"}'>option1</option>
    <option value='{"key1":"333","key2":"444"}'>option2</option>
</select>

on controller decode the request value as given below:

$values = json_decode($request->post('demo_select'));
$val1 = $values->key1;
$val2 = $values->key2;
echo "Value 1: ".$val1;
echo "Value 2: ".$val2;

output for the first option:

Value 1: 111
Value 2: 222

output for the second option:

Value 1: 333
Value 2: 444
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Saud Ahmad
  • 101
  • 7
1

Use a delimiter to separate the values.

<select name="myValues">
<option value="one|two">
</select>

<?php>
$value = filter_input(INPUT_POST, 'myValues');
$exploded_value = explode('|', $value);
$value_one = $exploded_value[0];
$value_two = $exploded_value[1];
?>
Chad C.
  • 21
  • 4
0

Duplicate tag parameters are not allowed in HTML. What you could do, is VALUE="1,2010". But you would have to parse the value on the server.

Witek
  • 6,160
  • 7
  • 43
  • 63
0

Instead of storing the options on the client-side, another way to do this is to store the options as sub-array elements of an associative/indexed array on the server-side. The values of the select tag would then just contain the keys used to dereference the sub-array.

Here is some example code. This is written in PHP since the OP mentioned PHP, but it can be adapted to whatever server-side language you are using:

<FORM action="" method="POST">
    <SELECT NAME="Testing">  
        <OPTION VALUE="1"> One </OPTION> 
        <OPTION VALUE="2"> Two </OPTION>
        <OPTION VALUE="3"> Three </OPTION>
    </SELECT>
</FORM>

PHP:

<?php
$options = array(
    1 => array('value1' => '1', 'value2' => '2010'),
    2 => array('value1' => '2', 'value2' => '2122'),
    3 => array('value1' => '3', 'value2' => '0'),
);
echo 'Selected option value 1: ' . $options[$_POST['Testing']]['value1'] . '<br>';
echo 'Selected option value 2: ' . $options[$_POST['Testing']]['value2'] . '<br>';
Cave Johnson
  • 6,499
  • 5
  • 38
  • 57
0

This may or may not be useful to others, but for my particular use case I just wanted additional parameters to be passed back from the form when the option was selected - these parameters had the same values for all options, so... my solution was to include hidden inputs in the form with the select, like:

<FORM action="" method="POST">
    <INPUT TYPE="hidden" NAME="OTHERP1" VALUE="P1VALUE">
    <INPUT TYPE="hidden" NAME="OTHERP2" VALUE="P2VALUE">
    <SELECT NAME="Testing">  
        <OPTION VALUE="1"> One </OPTION> 
        <OPTION VALUE="2"> Two </OPTION>
        <OPTION VALUE="3"> Three </OPTION>
    </SELECT>
</FORM>

Maybe obvious... more obvious after you see it.

MangoCat
  • 89
  • 5
0
        <select name="student" id="student">

                <option value="">Select Student</option>

                <option value="Student Name|Roll No">Student Name</option>

        </select>

        <input type="submit" name="submit" id="submit" value="submit"></form>
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 04 '22 at 12:26
0

i use data-attribute to get the value with simple javascript and blade template.

<select class="form-control" id="channelTitle" name="channelTitle" onchange="idChannels()">
                    @foreach($post['channels'] as $channels)
                        <option value="{{ $channels->channel_title }}" data-id="{{ $channels->channel_id }}">{{ $channels->channel_title }}</option>
                    @endforeach
                </select>

the data-id result here

<div class="form-group">
                <strong>Channel Id:</strong>
                <input type="text" name="channelId" id="channelId" class="form-control" placeholder="Channel Id">
            </div>

javascript

<script>
function idChannels(){
    var elem=document.getElementById("channelTitle");
    var id = elem.options[elem.selectedIndex].getAttribute('data-id');

    document.getElementById("channelId").value = id;
} </script>
reggi49
  • 460
  • 3
  • 11
-5

you can use multiple attribute

<SELECT NAME="Testing" multiple>  
 <OPTION VALUE="1"> One  
 <OPTION VALUE="2"> Two  
 <OPTION VALUE="3"> Three

Alex Kumbhani
  • 125
  • 2
  • 11