Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'd like to post two values in one drop down option and I'm not sure about the best way to approach it.

The drop down list pulls data in from an external service. This data is 'id' and 'name'.

When I select an option in the drop down and then press submit I want the 'id' and the 'name' to be posted.

My code looks like this:

<select name="data">
<option>Select a name</option>
<?php foreach($names as $name): ?>
    <option value="<?php echo $name['id']);?>">
       <?php echo $name['name']);?>
    </option>               
<?php endforeach; ?>
</select>

I've tried putting in a hidden input field, but that then doesn't render out the drop down (instead it just creates a list).

I am using both the id and name elsewhere, so I don't want to have to post just the id and then have to get the name again, hence I want to post both of them at the same time.

Any recommendations?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
536 views
Welcome To Ask or Share your Answers For Others

1 Answer

You cannot post two values unless both of them appear in the value attribute. You can place both in, separated by a comma or hyphen and explode() them apart in PHP:

// Place both values into the value attribute, separated by "-"
<option value="<?php echo $name['id'] . "-" . $name['name']);?>">
   <?php echo $name['name']);?>
</option>      

Receiving them in PHP

// split the contents of $_POST['data'] on a hyphen, returning at most two items
list($data_id, $data_name) = explode("-", $_POST['data'], 2);

echo "id: $data_id, name: $data_name";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...