如何获取此选项框的值并将其放在javascript变量中

时间:2013-09-29 16:37:10

标签: javascript php html ajax web

这是我的代码我想获取所选选项的值但是如何?

<?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>

2 个答案:

答案 0 :(得分:0)

使用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>

答案 1 :(得分:0)

试试这个纯粹的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;
}​;