如果用户只键入1个字符且未在列表中选择,我需要知道如何清除文本框?我在autocomplete.php中也有一个ajax,我需要将值发送到文本框。
这就是我现在所拥有的。
</script>
function changeAutoComplete (val) {
$( "#tags" ).autocomplete({
mustMatch: true,
source: 'autocomplete.php?selected='+val,
response: function(event, ui) {
if (ui.content.length === 0) {
$("#empty-message").text("No results found");
$(this).val("");
return false;
$("#empty-message").css({display:'', overflow: 'hidden'});
} else {
$("#empty-message").empty();
$("#empty-message").css({display:'none', overflow: 'hidden'});
}
}
});
}
</script>
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main" onchange="changeAutoComplete(this.value)">
<option value="" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<div class="demo-frame">
Tags
<input id="tags" name="items">
<div id="empty-message" style="display:none;"></div>
</div>
autocomplete.php
<?php
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["term"]);
$selected = $mysqli->real_escape_string($_GET["selected"]);
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' AND cat_code='$selected' GROUP BY id ORDER BY item" );
if($sql)
{
$str = array();
while($row=mysqli_fetch_array($sql))
{
$str[] = $row['item'];
}
echo json_encode($str);
}
?>
答案 0 :(得分:3)
在您的情况下,最好使用 blur
事件执行此操作。这里有这个
$('#tags').on('blur', function () {
if ($(this).val().length === 1) { //check for no. of characters entered
$(this).val(''); // clear the textbox
}
});
从您的评论中,最好使用 change
事件,
change: function (event, ui) {
if (!ui.item) {
$(this).val("");
$('#empty-message').show();
} else {
$('#empty-message').hide();
}
}