开发者

How to add values to Jquery UI Autocomplete text input

So I have a Jquery UI Autocomplete widget in my Jinja2 template which works great. However, I want the value of each program to be the program ID, not the name. IE: {{ p.id }} How do I set the name as the label and the id as the value?

<script>
$(function() {
    var programs = [
        {% for p in progr开发者_如何学Goams %}
        '{{ p.Name }}',
        {% endfor %}
    ];
    $( "#programs" ).autocomplete({
        source: programs
    });
});
</script>

<input type="text" name="program" id="programs" />


OK, this works!

The UI Autocomplete input is populated by the label attribute. The hidden_val attribute sets the hidden input with the select event.

<script>
$(function() {
    var programs = [
        {% for p in programs %}
        {
        hidden_val: "{{ p.id }}",
        label: "{{ p.Name }}"
        },
        {% endfor %}
    ];
    $( "#programs" ).autocomplete({
        delay: 0,
        source: programs,
        select: function(event, ui){
            $( "#program_val" ).val(ui.item.hidden_val);
        }
    });
});
</script>

<input type="text" id="programs" />
<input type="hidden" id="programs_val" />


Take a look at http://grover.open2space.com/content/using-jquery-autocomplete-ids that should do the trick!

Basically you supply the autocomplete textbox a list of name|id items. It will then show the name, and you only have to modify the textbox to put the id into a hidden form element using the .result() function. Like this:

$("#mytextbox")
  .autocomplete(data)
  .result(
    function (evt, data, formatted)
    {
      $("#hiddenIDbox").val(data[1]);
    }
);


This kind of works, but as soon as the autocomplete suggestion is selected, the item id appears in the input field.. confusing for the users, I guess. Any other ideas?

<script>
$(function() {
    var programs = [
        {% for p in programs %}
        {
        value: "{{ p.id }}",
        label: "{{ p.Name }}"
        },
        {% endfor %}
    ];
    $( "#programs" ).autocomplete({
        source: programs
    });
});
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜