Get Text From <option> Tag Using PHP

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 01:52:33
serialworm

In order to get both the label and the value using just PHP, you need to have both arguments as part of the value.

For example:

<select name="make">
    <option value="Text:5"> Text </option>
</select>

PHP Code

<?php
$parts = $_POST['make'];
$arr = explode(':', $parts);

print_r($arr);

Output:

Array(
  [0] => 'Text',
  [1] => 5
)

This is one way to do it.

What about this? I think it's the best solution because you have separated fields to each data. Only one hidden field which is updated at each change and avoids hardcoding mappings.

This inside HTML:

<select name='make' onchange="setTextField(this)">
<option value = '' selected> None </option>
<option value = '5'> Text 5 </option>
<option value = '7'> Text 7 </option>
<option value = '9'> Text 9 </option>
</select>
<input id="make_text" type = "hidden" name = "make_text" value = "" />
<script type="text/javascript">
    function setTextField(ddl) {
        document.getElementById('make_text').value = ddl.options[ddl.selectedIndex].text;
    }
</script>

This inside PHP:

<?php
$value = $_POST["make"];
$text = $_POST["make_text"];
?>

set the value of text to the value of the option tag, be it through static HTML markup or even if it's being generated by a server side script. You will only get the value attribute through POST

Another option however, on the server side, is to map the value ("5"), to an associative array, i.e.

<?php
$valueTextMap = array("5" => "Text");

$value = $_POST['make'];  //equals 5
$text = $valueTextMap[$value];  //equals "Text"
?>

You'll need to include that Text in the value to begin with (e.g.: <option value="5_Text"> Text </option> and then parse, or...

You could use javascript on the page to submit the text as another parm in the POST action.

I have always used a very elegant solution, similar to the ones already presented, which does not require a lot of additional code.

HTML

<select name="make">
  <option value="1:First Option">First Option Text</option>
  <option value="2:Second Option">Second Option Text</option>
  <option value="3:Third Option Text">Third Option Text</option>
</select>

PHP

$value = split(':', $make)[0];
$text = split(':', $make)[1];

Benefits of this method
Yes, there are definitely similarities to serialworm's answer, yet we minimize the code in our PHP block by inconspicuously converting to an array and picking the element required right away.

In my case, I use this exact short-hand code in a contact form where this one-liner (to get the selected department name) is critical to keeping the code looking clean.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!