使用ajax在下拉列表中实时搜索

时间:2017-06-29 16:03:41

标签: javascript html ajax

如何使用此代码进行ajax实时搜索,选择选项?

<script type="text/javascript">
$j(document).ready(function() {
    $j('#keyword').on('input', function() {
        var searchKeyword = $(this).val();
        if (searchKeyword.length >= 0) {
            $.post('search.php', { keywords: searchKeyword }, function(data) {
                $j('ul#content').empty()
                $.each(data, function() {
                    $j('ul#content').append('*<a href="reserve.php' + this.id + '">' + this.title + '</a>');
                });
            }, "json");
        }
    });
});
</script>

此代码适用于输入类型[&#39; text&#39;],如:

 <input type="text" class="form-control" id="keyword" />

但我希望它适用于:

<select name="field" id="keyword">
<option value="1">sometext</option>
<option value="2">sometext</option>
<option value="3">sometext</option>
<option value="4">sometext</option>
</select>

如何使用上面的代码获取所选选项的值?

已解决:

<script type="text/javascript">
$j(document).ready(function() {
    $j('#keyword').on('change', function() {
        var searchKeyword = $("#keyword option:selected").val();;
        if (searchKeyword.length >= 0) {
            $.post('search.php', { keywords: searchKeyword }, function(data) {
                $j('ul#content').empty()
                $.each(data, function() {
                    $j('ul#content').append('*<a href="reserve.php' + this.id + '">' + this.title + '</a>');
                });
            }, "json");
        }
    });
});
</script>

1 个答案:

答案 0 :(得分:2)

<script type="text/javascript">
$j(document).ready(function() {
$j('#keyword').on('change', function() {
    var searchKeyword = $("#keyword option:selected").val();;
    if (searchKeyword.length >= 0) {
        $.post('search.php', { keywords: searchKeyword }, function(data) {
            $j('ul#content').empty()
            $.each(data, function() {
                $j('ul#content').append('*<a href="reserve.php' + this.id + '">' + this.title + '</a>');
            });
        }, "json");
    }
});
});
</script>