我正在使用 jquery ui 自动完成从我的数据库中获取汽车、零件和服务,我通过在最后添加 span 来区分两个或三个记录类型。但是当我选择任何值时,它会在输入中显示跨度 html 代码和代码,我该如何解决这个问题?
php:
public function partCodeAutoc(Request $request)
{
$return_arr1 = [];
$return_arr2 = [];
$return_arr3 = [];
$type = $request->code_type;
$part_code = $request->term;
$column = "code";
$column2 = "car_code";
$query = Cars::where($column2, "LIKE", "%" . $part_code . "%")->where('car_status',3)->get();
if ($query->count() > 0) {
foreach ($query as $rows) {
$newdata = $rows->$column2.' <span class="badge badge-light-secondary" style="float:right;">Car</span>';
array_push($return_arr1, $newdata);
}
$return_arr2 = array_unique($return_arr1);
foreach ($return_arr2 as $key => $value) {
$row_array["label"] = $value;
$row_array["value"] = $value;
array_push($return_arr3, $row_array);
}
echo json_encode($return_arr3);
}
js:
$("#part_code").autocomplete({
source: function (request, response) {
if ($("#service-chk").is(":checked")) code_type = 1;
else code_type = 0;
$.ajax({
url: "partCodeAutoC",
type: "POST",
dataType: "json",
data: {
code_type:code_type,
term: request.term,
},
success: function (data) {
response(data);
},
});
},
minLength: 1,
select: function (event, ui) {
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<div>" + item.label + "</div>")
.appendTo(ul);
};
您看到了 span 标签,因为您没有删除它们,而您必须这样做。
您可以这样修改它:
$("#part_code").autocomplete({
source: function (request, response) {
if ($("#service-chk").is(":checked")) code_type = 1;
else code_type = 0;
$.ajax({
url: "partCodeAutoC",
type: "POST",
dataType: "json",
data: {
code_type: code_type,
term: request.term,
},
success: function (data) {
response(data);
},
});
},
minLength: 1,
select: function (event, ui) {
// Extracting text without HTML tags
var selectedValue = ui.item.value.replace(/<[^>]+>/g, '');
// Set the input value to the extracted text
$(this).val(selectedValue);
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
// Render each item without HTML tags
return $("<li>")
.append("<div>" + item.label.replace(/<[^>]+>/g, '') + "</div>")
.appendTo(ul);
};
这样,选择项目时就不会包含 HTML 标签
$("#part_code").autocomplete({
source: function (request, response) {
if ($("#service-chk").is(":checked")) {
code_type = 1;
} else {
code_type = 0;
}
$.ajax({
url: "partCodeAutoC",
type: "POST",
dataType: "json",
data: {
code_type: code_type,
term: request.term,
},
success: function (data) {
response(data);
},
});
},
minLength: 1,
select: function (event, ui) {
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var $li = $("<li>");
var labelWithoutTags = item.label.replace(/<\/?[^>]+(>|$)/g, "");
$li.append("<div>" + labelWithoutTags + "</div>");
return $li.appendTo(ul);
};