我有一个选择和一个datalist html。 Select列出了几个州,如纽约州或新泽西州。 Datalist列出学校名称。这是由ajax< - >生成的。 php,因为学校名称取决于州。
但是,当我调用Datalist的值时,返回是未定义的。
form id="search_school">
<strong>Select State:</strong>
<select id="selectState" onchange="selectState()">
<option value="NA" > </option>
<option value="NJ" >New Jersey</option>
<option value="NY">New York</option>
</select>
<div id="test"></div>
<div id="displaySchools"></div>
<input id="searchBTN" type="button" value="Search"/><br>
</form>
<script>
$(document).ready(function(){
$('#selectState').change(function(){
var selectState = $('#selectState').val();
if(selectState != '')
{
$.ajax({
url:"selectState.php",
method:"POST",
data:{selectState:selectState},
success:function(data)
{
$("#displaySchools").html(data);
}
});
}
else
{
alert("All Fields are required");
}
});
});
这部分是问题所在。我也做了GetElementById,但仍然返回undefined。
$(document).ready(function(){
var contents = $('#schools');
$("#searchBTN").click(function(){
$("#test").html(contents);`
});
});
selectState.php
$selectState = $_POST['selectState'];
switch ($selectState) {
case "NJ":
$msg='<strong>Enter School:</strong>
<input list="schools" name="schools">
<datalist id="schools">
<option value="New Jersey Institute of Technology"></option>
<option value="Rutgers University"></option>
<option value="Princeton University"></option>
</datalist>';
echo $msg;
break;
case "NY":
$msg='<input list="schools" name="schools">
<datalist id="schools">
<option value="Columbia University"></option>
<option value="Cornell University"></option>
<option value="New York University"></option>
</datalist>';
echo $msg;
break;
default:
echo "error";
}
Chrome开发人员工具的结果看起来没有问题。
<div id="displaySchools">
<strong>Enter School:</strong>
<input list="schools" name="schools">
<datalist id="schools">
<option value="New Jersey Institute of Technology"></option>
<option value="Rutgers University"></option>
<option value="Princeton University"></option>
</datalist>
</div>
答案 0 :(得分:0)
我提供了输入标签名称和ID,并使用它来显示学校名称。
$selectState = $_POST['selectState'];
switch ($selectState) {
case "NJ":
$msg='<strong>Enter School:</strong>
<input list="schools" name="schools" name="schoolName" id="schoolName">
<datalist id="schools">
<option value="New Jersey Institute of Technology"></option>
<option value="Rutgers University"></option>
<option value="Princeton University"></option>
</datalist>';
echo $msg;
break;
case "NY":
$msg='<input list="schools" name="schools" name="schoolName" id="schoolName">
<datalist id="schools">
<option value="Columbia University"></option>
<option value="Cornell University"></option>
<option value="New York University"></option>
</datalist>';
echo $msg;
break;
default:
echo "error";
}
然后jquery会:
$("#searchBTN").click(function(){
var schoolName = $('#schoolName').val();
$("#test").html(schoolName);
});