使用php获取所选选项的文本 [英] get the text of the selected option using php

查看:66
本文介绍了使用php获取所选选项的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



in the following:

<form  action="test.php"  method="POST">  
    <select id="test" name="test">
     <option value="1">Test One</option>
     <option value="2">Test Two</option>
    </select>
</form>

在test.php中,我可以得到如下的1或2:

in test.php, I can get 1 or 2 as follow:

$result=$_POST['test'];

如何获取所选选项的文本(即Test One或Test Two )使用PHP

How can I get the text of the selected option (i.e. "Test One" or "Test Two") using php

推荐答案

这不是通过PHP单独完成的。 PHP脚本只能查看发布的信息(对于发布的选定的选项,) 。您可以使用javascript来修改隐藏的 input 字段,其中包含选定的选项的文本内容,在 $ _ POST 数组中:

This is not something that can be done through PHP alone. The PHP script can only "see" the information which is posted (the value for the selected option that is posted). You can use javascript to alter a hidden input field with the text contents of a selected option, and this will be included in the $_POST array:

<form  action="test.php"  method="POST">  
    <select id="test" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
     <option value="1">Test One</option>
     <option value="2">Test Two</option>
    </select>

<input type="hidden" name="test_text" id="text_content" value="" />
</form>

这会使 $ _ POST ['test_text'] 可用于所选索引(但您也应该在加载页面时强制 onchange()函数,以便即使用户离开选择字段时也会填充该函数在默认值。

This will make the $_POST['test_text'] available with the selected index (but you should also force the onchange() function when the page loads so that it will be populated even if the user leaves the select field at the default value.

这篇关于使用php获取所选选项的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆