javascript - 获取更改时选择输入的值

标签 javascript php jquery

我试图获取选择输入中所选选项的值,但它不起作用。当我更改选项时,它应该显示一个警告框,但什么也没有发生。这是我的代码。

<html>
<head>
<?PHP

$content ="";
$mammalArray = array();
$otherArray = array();
array_push($mammalArray,"dog");
array_push($mammalArray,"cat");
array_push($mammalArray,"pig");
array_push($otherArray,"bird");
array_push($otherArray,"fish");


$content .= "<select><option value='0'>Please Select a Pet Item</option>";
$content .= "<optgroup label='Mammals'>";

foreach($mammalArray as $animal=>$pet)
{
    $content .= "<option>" . $pet . "</option>";
}

$content .= "</optgroup><optgroup label='Other'>";

foreach($otherArray as $animal=>$pet)
{
   $content .= "<option>" . $pet . "</option>";
}
$content .= "</optgroup></select>";
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
            $("select").change(function(){
            // Do something here.
            //alert("hello");
            var option = $(this).find('option:selected').val();
            alert(option);
            });
        </script>

</head>
<body>
<?php
echo($content);
?>


</body>
</html>

最佳答案

您的选项没有任何值(value),您需要在脚本中包含以下内容:

$(function() {
   $("select").change(function(){
       var option = $(this).find('option:selected').val();
      alert(option);
   });
)};

关于javascript - 获取更改时选择输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35204556/

相关文章:

javascript - 替换正则表达式中的文本

javascript - Jquery SlideToggle 的范围问题

php - Pspell 仅使用自定义词典

javascript - 处理事件后将颜色放入元素中

javascript - 如何从子指令的链接函数调用父指令的链接函数

javascript - 简单的 prettyprint 程序不工作

php - mysql+php查询查询两张表得到结果

php - 将 blob 保存到 php 中的图像文件

jquery - 如何使用jquery监听返回的json对象

php - 按钮没有被隐藏