很棒的完整设置标签文本字段和隐藏字段值


Awesomplete set label text field and hidden field value

我使用awescomplete简单的文本字段自动完成。我有一个具有标签和值的数组,当选择某些内容时,我希望它完成文本并将值(在本例中为ID)添加到隐藏字段中。

文档

有人知道怎么做吗?

代码示例:HTML:

<input type="text" id="title" name="title" class="form-control" placeholder="Titel" required />
<input type="hidden" id="id" name="id">
PHP:

<?php
$titles = array();
    foreach ($data as $title){
            $titles[] = array(
                "label" =>  $title->title,
                "value" => $title->id,
            );
    }
?>

JS

<script type="text/javascript">
    //array with all titles and id from a php array
    var jArray = <?php echo json_encode($titles); ?>;
    var input = document.getElementById("title");
    var input2 = document.getElementById("id");
    new Awesomplete(input, {
        list: jArray
    });

</script>

您可以使用awescomplete -selectcomplete事件来设置隐藏输入的val

            window.addEventListener("awesomplete-selectcomplete", function(e){
                input2.value = e.text.value;
            }, false);

去https://leaverou.github.io/awesomplete/#events了解更多的事件,但引用它,"回调将传递一个对象的文本属性包含选择的建议。"

这样做:

<input id="myinput-hidden" name="lang" type="hidden" />
<input id="myinput" />
var hidden = $("#myinput-hidden");
new Awesomplete("#myinput", {
    list: [["Ada", 1], ["Java", 2], ["JavaScript", 3], ["Brainfuck", 4], ["LOLCODE", 5], ["Node.js", 6], ["Ruby on Rails", 7]],
    // the only function you need to override:
    replace: function(suggestion) {
        this.input.value = suggestion.label; // default replace() inserts suggestion.value to input
        hidden.value = suggestion.value;
    }
});