在< select>选项中嵌入多个值 [英] embedding multiple values in options of <select>
问题描述
我需要在下拉列表的每个选项中嵌入2个值,然后需要能够将它们传递给JavaScript函数。
< select onChange =display(<?= $ manufacturer_id?>,<?= $ modelID?> ;,this.value1,this.value2);>
..
..
echo< option value1 = \。$ variantID。\value2 = \。$ month_year。\> ;。$ products_variant。。$ month_year。< / option>;
..
..
< / select>
正如您所看到的,这个HTML代码是由PHP生成的,我需要从数据库中提取的这两个值传递给一个JS函数。
我对这样做有更好的方法建议吗?
您无法在选项中添加许多值。
,您可以使用数据集( html5),例如:
< select id =myselect>
< option data-this =foodata-that =bar>
< / select>
javascript读取这些值为:
var d = document.getElementById(myselect);
var _this = d.options [d.selectedIndex] .dataset [this];
var _that = d.options [d.selectedIndex] .dataset [that that]];
如果您不想混淆数据集,可以存储JSON对象:
...
< option value ='<?php echo json_encode(array(foo=> 1,栏=→2)); ?>>
...
并提取数据:
var d = document.getElementById(myselect);
var option_value = JSON.parse(d.options [d.selectedIndex] .value);
您选择
: 更改此项: I need to embedd 2 values in each of the options of a drop down list and then need to be able to pass both of them to a JavaScript function. As you can see this HTML code is generated by PHP, I need these two values fetched from database to passed to a JS function. I am open to suggestions on better way of doing this? you cannot add many values in an option.
instead you can use datasets (html5), like: the javascript to read these values is: if you dont want to mess with datasets, you can store a JSON object: and extract the data like: you choose EDITED: change this:
这篇关于在< select>选项中嵌入多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
< select的onChange = 显示(小于?= $ manufacturers_id>?,< = $ modelID>,这一点); >
function display(manufacturers_id,modelid,obj){
... json way
var option_value = JSON.parse(obj.options [obj.selectedIndex] .value);
// option_value.foo = 1;
...数据集方式
var _this = obj.options [obj.selectedIndex] .dataset [this];
// _这将具有foo值
<select onChange="display(<?=$manufacturers_id?>,<?=$modelID?>,this.value1,this.value2);">
..
..
echo "<option value1=\"".$variantID."\" value2=\"".$month_year."\">".$products_variant." ".$month_year."</option>";
..
..
</select>
<select id="myselect">
<option data-this="foo" data-that="bar">
</select>
var d = document.getElementById("myselect");
var _this = d.options[d.selectedIndex].dataset["this"];
var _that = d.options[d.selectedIndex].dataset["that"];
...
<option value='<?php echo json_encode(array("foo"=>1,"bar"=>2)); ?>'>
...
var d = document.getElementById("myselect");
var option_value = JSON.parse( d.options[d.selectedIndex].value );
<select onChange="display(<?=$manufacturers_id?>,<?=$modelID?>,this);">
function display(manufacturers_id,modelid,obj) {
... json way
var option_value = JSON.parse(obj.options[obj.selectedIndex].value);
// option_value.foo = 1;
... dataset way
var _this = obj.options[obj.selectedIndex].dataset["this"];
// _this will have the "foo" value
}