通过以下方法更改了<select>
在成功响应时的值:
jQuery('#vat').val(response);
使用此方法,返回的值可以放置到textbox
中,但需要更改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>
发布于 2018-09-16 12:04:24
您是对的,<select>
值将随$("#vat").val(1)
更改。然而,这不会创建一个新的<option>
。如果有一个<option value="1">
,那么这个选项就会显示出来。因为它不存在,所以HTML没有显示和显示默认的<option>
of <select>
。
您需要创建一个<option>
并将其附加到<select>
中。
以下是关于成功的jQuery:
var newOption = `<option value=` + response + `>` + response + `</option>`;
$("#vat").append(newOption);
$("#vat").val(response);
https://stackoverflow.com/questions/52356088
复制