如何在选项字段中发布两个值? [英] How to post two values in an option field?

查看:78
本文介绍了如何在选项字段中发布两个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个下拉选项中发布两个值,我不确定最好的方法。



下拉列表拉数据来自外部服务。这个数据是'id'和'name'。



当我在下拉列表中选择一个选项,然后按提交,我想要'id'和'name'



我的代码如下所示:

 < ;选择name =data> 
< option>选择名称< / option>
<?php foreach($ names as $ name):?>
< option value =<?php echo $ name ['id']);?>>
<?php echo $ name ['name']);?>
< / option>
<?php endforeach; ?>
< / select>

我试着把一个隐藏的输入框放进去,但是不会渲染掉(相反,它只是创建一个列表)。



我在别处使用id和name,所以我不想只发布id,然后必须再次获得名称,因此我想同时发布他们两个。



任何建议吗?

解决方案

除非它们出现在属性中,否则不能发布两个值。



<$ p $您可以将两者放在一起,用逗号或连字符分隔,并且 explode() p> //将两个值放入值属性中,用 - 分隔

在PHP中接收它们

  //在连字符上分割$ _POST ['data']的内容,最多返回两个项目
list($ data_id,$ data_name)= explode( - ,$ _POST ['data'],2);

echoid:$ data_id,name:$ data_name;


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?

解决方案

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";

这篇关于如何在选项字段中发布两个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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