更改了 <select>
的值来自 API 的成功响应:
jQuery('#vat').val(response);
通过这个返回值可以放入 textbox
,但需要更改a combobox
的选定值.
如何实现这一点?
这是 jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getVat() { // Do an Ajax request to retrieve the product price
console.log("getVat before ajax", jQuery('#product_name').val());
jQuery.ajax({
url: './get/vat/get1.php',
method: 'POST',
data: {'id' : jQuery('#product_name').val()},
success: function(response){
console.log("getPrice after ajax", jQuery('#product_name').val());
jQuery('#vat').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
该脚本在 #vat
时有效是 textbox
但不是在#vat
时是 combobox
.
更新: 这是用于组合框的脚本:
<?php
$dbname = 'db';
$dbuser = 'root';
$dbpass = 'pass';
$db = new mysqli('localhost', $dbuser, $dbpass, $dbname);
if (!$db) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
?>
<select style="width:100%" id="vat" name="vat">
<option value = "0">No VAT</option>
<?php
$queryusers = "SELECT id, internal_id, name FROM vat";
$db = mysqli_query($db, $queryusers);
while ( $d=mysqli_fetch_assoc($db)) {
echo "<option value='".$d['id']."'>".$d['internal_id']." | ".$d['name']."</option>";
}
?>
</select>
更新2:
所选值更改为“1”。但脚本仍然显示<option value = "0">No VAT</option>
。有人知道我如何更新显示的数据吗?
更新3:
当我运行以下脚本时,我只是得到了一个额外的选项。表示为所选值的值仍然相同:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getVat() { // Do an Ajax request to retrieve the product price
console.log("getVat before ajax", jQuery('#product_name').val());
jQuery.ajax({
url: './get/vat/get1.php',
method: 'POST',
data: {'id' : jQuery('#product_name').val()},
success: function(response){
// and put the price in text field
var newOption = "<option value=" + response + ">" + response + "</option>";
$("#vat").append(newOption);
$("#vat").val(response);
getPrice();
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
最佳答案
你说得对<select>
值将更改为 $("#vat").val(1)
。但是,这不会创建新的 <option>
。如果有 <option value="1">
那么这个选项就会被显示。由于它不存在,因此 HTML 没有任何内容可显示并显示默认 <option>
的<select>
.
您需要创建一个 <option>
并将其附加到 <select>
.
这是成功的 jQuery:
var newOption = `<option value=` + response + `>` + response + `</option>`;
$("#vat").append(newOption);
$("#vat").val(response);
关于javascript - 如何用jquery动态添加<select> <option>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52356088/