2016-02-04 146 views
0

我正在尝试在选择输入中获取所选选项的值,但它不起作用。当我改变选项时它应该显示一个警告框,但没有任何事情发生。这是我的代码。获取选择输入更改的值

<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> 
+0

首先,值”;? –

回答

0

您的选择有没有价值,所以你需要更新你的foreach循环包括一个。例如: - :没有设置你<option>标签的value属性有

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

-

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

然后使其包裹在$(function() {});,以确保该文件已准备好运行之前更新您的jQuery将是没有价值的$(this).find('option:selected').val();

3

您的期权没有价值,你需要环绕你的脚本如下:之前你的HTML DOM中的设置被执行

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

您的JavaScript。无论是包装你的代码在$(document).on('ready')处理或只是你</body>之前把它,你的HTML后:

$(document).on('ready', function(){ 
    $("select").change(function(){ 
     var option = $(this).find('option:selected').val(); 
     alert(option); 
    }); 
}); 
0
<script type="text/javascript"> 
    $(document).on("change", "select", function() { 
     // Do something here. 
     //alert("hello"); 
     var option = $(this).val(); 
     alert(option); 
    }); 
</script>