0

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 programs %}
        '{{ p.Name }}',
        {% endfor %}
    ];
    $( "#programs" ).autocomplete({
        source: programs
    });
});
</script>

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

3 Answers 3

1

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" />
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

I believe this article is geared at the now deprecated jQuery autocomplete plugin, not the jQueryUI one (which does not have a result function)
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.