自动完成文本框,显示名称但存储ID

时间:2018-06-20 07:37:07

标签: javascript php jquery ajax mysqli

  

header.php文件,用于发送分类ID和返回子类别名称

 <?php 
     $conn = mysqli_connect("localhost", "root", "", "iraa");
 ?>
 Category :
<select  id="category_id" name="cat_id" required=""  class="form-control" tabindex="2" onselect ="getSubcat()">
    <option value="">-- Select --</option>
    <?php 
        $sql = "SELECT category_id,category_name FROM categories_master";
        $result = mysqli_query($conn, $sql);
        while ($data=mysqli_fetch_array($result)) {                              
    ?>
    <option value="<?php echo $data['category_id'] ?>"><?php echo $data['category_name'] ?></option>
    <?php } ?>
</select>

Sub Category : 
<select id="sub_cat_id" required  name="sub_cat_id"  class="form-control " tabindex="2">
    <option value="">-- Select --</option>
</select>

<script src="js/jquery-1.12.4.js"></script>
<script src="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet">
<script type="text/javascript">
    $('#category_id').editableSelect();
    function getSubcat() {
        var category_id=$("#category_id").val();
        alert(category_id);
        $.ajax({
            url: 'get_subcategory.php',
            type: 'POST',
            data: {category_id: category_id},
        })
        .done(function(response) {
            $('#sub_cat_id').html(response);
        });
    }
</script>
  

get_subcategory.php文件,用于获取ajax响应并返回子类别

<?php 
$conn = mysqli_connect("localhost", "root", "", "iraa");
$sql = "SELECT sub_category_id,sub_category_name FROM sub_categories_master WHERE category_id='$_POST[category_id]'";
$result = mysqli_query($conn, $sql);
while ($data=mysqli_fetch_array($result)) {                              
?>
<option value="<?php echo $data['sub_category_id'] ?>"><?php echo $data['sub_category_name'] ?></option>
  

此返回类别名称,但我希望类别ID而不是类别名称   enter image description here

1 个答案:

答案 0 :(得分:1)

在使用jQuery editableSelect插件时,您可能需要查看Listen changes

示例:

Category :
<select  id="category_id" name="cat_id" required="" class="form-control" tabindex="2">
    <option value="">-- Select --</option>
    <option value="1">First</option>
    <option value="2">Second</option>
</select>
<pre>Last selected: <span id="last-selected"></span></pre>

<script type="text/javascript">
    $('#category_id')
    .editableSelect()
    .on('select.editable-select', function (e, li) {
        $('#last-selected').html(
            li.val() + '. ' + li.text()
        );
    });
</script>

在此处查看实际操作:http://jsfiddle.net/dpaf13n7/7/

所以我猜您正在寻找的数据是li.val()

如果您编辑选择选项,则将没有值。

希望这对您有所帮助。