如果当前值不在列表中,则自动完成返回空白

时间:2014-02-21 09:06:53

标签: php jquery mysql

我的代码在http://jsfiddle.net/qv94t/7/处理正常。但是当选项值来自php时,函数无法正常工作。我使用ajax生成选项值,但如果我在同一页面中回显选项值而不使用ajax,它也会出现相同的错误。

为什么?请帮忙

我的ajax

getajax.php

<?php
if (isset($_POST["mainlist_id"])) {
    $mysqli = new mysqli("localhost", "root", "", "2015");
    $main = $mysqli->real_escape_string($_POST["mainlist_id"]);


$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");

    while($row = $result1->fetch_assoc())
    {
    ?>
    <option class="eachop" value ="<?php echo $row['item'];?>"><?php echo $row['item'];?></option>';
<?php
    }
    }
?>

这是我的完整代码,我忘了添加我的ajax和下拉列表。有人帮忙吗?

ajax.php

 <?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">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<input list="languages" id="none"></input>
<datalist id="languages" name="options">
    <option value=""></option>
</datalist>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
<input type="submit" name="submit" value="Submit" />

<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#languages').html(data);
}
});
});
</script>
<script>
    var validOptions = [];
    $("option").each(function () {
        validOptions.push($(this).val())
    });
    previousValue = "";
    console.log(validOptions)
    $('#none').autocomplete({
        autoFocus: true,
        source: validOptions
    }).keyup(function () {
        var isValid = false;
        for (i in validOptions) {
            if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
                isValid = true;
            }
        }
        if (!isValid) {
            this.value = previousValue
        } else {
            previousValue = this.value;
        }
    });
</script>

1 个答案:

答案 0 :(得分:0)

你必须回显值,然后只有ajax获取值并在代码下面显示使用....

 <?php
    if (isset($_POST["mainlist_id"])) {
        $mysqli = new mysqli("localhost", "root", "", "2015");
        $main = $mysqli->real_escape_string($_POST["mainlist_id"]);


    $result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");

        while($row = $result1->fetch_assoc())
        { 
        echo "<option class=\"eachop\" value =\"".$row['item']."\">".$row['item']."</option>";
        }
     }
    ?>