PHP get dropdownlist select option value

2019-01-25 18:44发布

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!

4条回答
Lonely孤独者°
2楼-- · 2019-01-25 19:16

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']);
   //...
?>
查看更多
Fickle 薄情
3楼-- · 2019-01-25 19:21

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.

查看更多
对你真心纯属浪费
4楼-- · 2019-01-25 19:25

You cannot get value_text from POST data. One solution is to populate the hidden field after choosing the option via JavaScript.

查看更多
仙女界的扛把子
5楼-- · 2019-01-25 19:26

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.

查看更多
登录 后发表回答