doufang3001 2012-11-19 06:52
浏览 72

如何使用JavaScript更改select标签的值?

I have two pages . "page1.php" "page2.php"

In page1.php ,

<a href="page2.php?c=Category1">Category1</a>
<a href="page2.php?c=Category2">Category2</a>
<a href="page2.php?c=Category3">Category3</a>

In page2.php,

<?php
    $c=$_GET['c'];
    echo '<script>'
    , 'chgvalues("'.$c.'");'
    , '</script>';
?>
<select id="mySelect">
    <option>Category1</option>
    <option>Category3</option>
    <option>Category2</option>
</select>

In chgvalues(c),

function chgvalues(c)
{
    document.getElementById("mySelect").selected =true;
}

But this ain't working for me. What I want to do is , when a user clicks on a link on page 1 then the page 2 has the select value automatically set .

I think I am wrong in this chgvalues function.

  • 写回答

5条回答 默认 最新

  • dongshai2022 2012-11-19 06:55
    关注

    Change page2.php to:

    <select id="mySelect">
    <option id="Category1">Category1</option>
    <option id="Category3">Category3</option>
    <option id="Category2">Category2</option>
    </select>
    <?php
    $c=$_GET['c'];
    echo '<script>'
    , 'chgvalues("'.$c.'");'
    , '</script>';
    ?>
    

    Your script is running before the options are in the DOM, and there are no IDs on the options so they don't match getElementById.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度