【问题标题】:how to get value of this option box and put it in javascript variable如何获取此选项框的值并将其放入 javascript 变量中
【发布时间】:2013-09-30 00:46:19
【问题描述】:
这是我的代码,我想获取所选选项的值,但是如何获取?
<?php
$sql = "SELECT * FROM `category`";
$category = mysql_query($sql); ?>
<select>
<?php
while ($row = mysql_fetch_array($category)) {
echo "<option id='cat' value='" . $row['catid'] ."'>" . $row['catname'] ."</option>";
}
?>
</select>
【问题讨论】:
标签:
javascript
php
html
ajax
web
【解决方案1】:
使用 jQuery(http://api.jquery.com/selected-selector/),
说你有:
<select name="garden" multiple="multiple">
<option>Flowers</option>
<option selected="selected">Shrubs</option>
<option>Trees</option>
<option selected="selected">Bushes</option>
<option>Grass</option>
<option>Dirt</option>
</select>
<div></div>
<script>
$( "select" )
.change(function() {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$( "div" ).text( str );
})
.trigger( "change" );
</script>
【解决方案2】:
试试这个纯 javascript 解决方案(不带 jQuery)
HTML(通过 - 属性 id 更改您当前的 SELECT html 标签)
<select id="myselect">
JAVASCRIPT
var myvariable = null;
document.getElementById('myselect').onchange = function(e) {
myvariable = this.options[this.selectedIndex].value;
};