In my dropdownlist I have two different values for each option. How can I retrieve both? Let me illustrate what开发者_运维技巧 I mean.
<select name="my_ddl">
<option value="<?php $value_Id ?>"><?php $value_text ?></option>
<option value="<?php $value_Id ?>"><?php $value_text ?></option>
</select>
When the form is posted, I want to be able to get both the $value_id and $value_text of the selected option. How can I do this?
$_POST['my_ddl'] only gets one value not both.
In asp.net I could do this simply by referring to my_ddl.Value and my_ddl.Text.
Thank you!
Strictly, this is not possible.
What you could do is use a delimiter in your value
attribute:
<select name="my_ddl">
<option value="<?php echo $value_Id ?>|<?php echo $value_text ?>"><?php echo $value_text ?>
</option>
</select>
And...
<?php
list($id, $text) = explode('|', $_POST['my_ddl']);
//...
?>
Another strange way of doing it is:
<select name="my_ddl">
<option value="<?php echo $value_Id ?>[<?php echo $value_text ?>]">
<?php echo $value_text ?>
</option>
</select>
Then when you process it you can do this or maybe even something more simple:
foreach ($_POST['my_dd1'] as $value_Id => $value_text) {
$value_Id = $value_Id;
$value_text = $value_text;
}
Because php treats the [] as meaning the string is an array and so you instantly have an associative array. I agree though that if you put it there in the first place you ought to be able to just look it up again in the code rather than rely on this.
If you're using PHP to populate the text for the <option>
then you can probably just look the value up on the server. Perhaps you just need to use the $value_id to look up the text in a database table?
If not, you could include a hidden field on your form and use JavaScript to update that hidden field with the text every time a new value is selected.
You cannot get value_text from POST data. One solution is to populate the hidden field after choosing the option via JavaScript.
精彩评论