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