各位好:
想請教我該怎麼更新datalist option呢?
我有一個下拉選單,我希望選了之後去更新另一個下拉選單
我用select option的OK,但改datalist就不行..
可以幫我看一下是哪裡有錯嗎?謝謝
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<script type="text/javascript">
function show_book_num(a)
{
var result=document.getElementById('company').value;
var words="";
if (window.XMLHttpRequest)
{// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ words =xmlhttp.responseText.split("\n");
//words確定有資料,資料範例:螺絲X100,螺帽X50......
var option='';
for(var i=0;i<words.length-1;i++)
{ option+='<option value="' + words[i] + '" />';
document.work_case.options[i]=new Option(words[i],words[i]);
document.work_case.length=words.length-1;
}
}
}
xmlhttp.open("GET","sql_company.php?q="+result,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div class="container">
<form id="myform" name="myform" action="t.php" method="post" enctype="multipart/form-data">
<div class="container" >
<div class="form-group row" >
<?php
require 'db.php';
?>
<!--line 1-->
<div class="col-12 col-xs-12 col-sm-4 col-md-4 col-lg-4 mt-2 mb-2" >
<label>客戶:</label>
<input list="company-list" id="company" class="form-control" onchange="show_book_num(this.id)">
<datalist id="company-list" > <!--選項-->
<?php
$sql_search2 = "select company from `customer`";
$result_n = mysqli_query($db, $sql_search2);
while ($row = mysqli_fetch_array($result_n)) {
?>
<option value="<?=$row['company'];?>">
<?php
}
?>
</datalist>
</div>
<!--line 3-->
<div class="col-12 col-xs-12 col-sm-8 col-md-8 col-lg-8 mt-2 mb-2">
<label>購買紀錄:</label>
<input list="case-list" id="work_case" class="form-control" >
<datalist id="case-list" >
<option value="例:螺絲X100....."> <!--更新這裡-->
</datalist>
</div>
</form>
</div>
</body>
</html>
目前用F12顯示
document.work_case.options[i]=new Option(words[i],words[i]);
錯誤
試了好像不行用option obj直接指定位置
應該是DOM結構不大一樣
只能直接創option元素用append的方法加入
var datalist = document.getElementById('case-list')
var option1 = document.createElement("option");
option1.value = "螺絲X100";
datalist.appendChild(option1)
看看w3school的介紹似乎也沒有text能塞
只有我會這麼不務正統嗎?
jQuery
$("#mySelect").append(new Option("a001","選項a001"));
或是
$('<option/>')
.val("a001")
.text('選項a001')
.appendTo('#mySelect')
真心覺得..正統的方法寫的太多,日後維護會更辛苦,為了我的專案能長久活下去,我還是會用簡單的方法,解決當務之急