Awesomplete设置标签文本字段和隐藏字段值

时间:2016-09-12 13:41:03

标签: javascript php jquery autocomplete

我使用Awesomplete进行简单的文本字段自动填充。我有一个带有标签和值的数组,当选择了某些内容时,我想用它来补充文本并将值(在本例中为ID)添加到隐藏字段中。

docs

任何人都知道怎么做?

代码示例:

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>

2 个答案:

答案 0 :(得分:1)

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

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

转到https://leaverou.github.io/awesomplete/#events了解有关事件的更多信息,但要引用它,&#34; 回调将传递一个带有包含所选建议的文本属性的对象。&#34 ;

答案 1 :(得分:0)

这样做:

<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;
    }
});