Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8288189
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T12:13:56+00:00 2026-06-08T12:13:56+00:00

I want to fill a text input in my form using an autocomplete widget

  • 0

I want to fill a text input in my form using an autocomplete widget that I have created using jquery ui. Everything works exactly how I want to, except when the form is submitted.

The problem is that when I submit the form, the text input is automatically reseted (I don’t know why) and after that, the page reloads saying that the field is required (just validation working how it’s supposed to). Of course, if it didn’t reset the field everything would go fine.

I dont know if my select event of the autocomplete is working fine, here is the code:

 select : function (e, ui) {
   // I create a new attribute to store de database primary key of this option. This is
   // usefull later on.
   $('#%(input_id)s').attr('itemid', ui.item.real_value);

   // I set the input text value's.
   $('#%(input_id)s').val(ui.item.label);
 }

Here is the full code of the autocomplete:

class AutocompleteTextInputWidget (forms.TextInput):

  def media(self):
    js = ("/js/autocomplete.js", "pepe.js")

  def __init__(self, source, options={}, attrs={}):
    self.options = None
    self.attrs = {'autocomplete': 'off'}
    self.source = source
    self.minLength = 1
    self.delay = 0
    if len(options) > 0:
        self.options = JSONEncoder().encode(options)

    self.attrs.update(attrs)

  def render(self, name, value=None, attrs=None):
    final_attrs = self.build_attrs(attrs)        
    options = ''

    if value:
        final_attrs['value'] = escape(value)

    if isinstance(self.source, list) or isinstance(self.source, tuple):
        # Crea un Json con las opciones.
        source = '[' 
        for i in range(0, len(self.source)):
            if i > 0:
                source += ', '
            source += '"' + self.source[i] + '"'
        source += ']'

        options = u'''
            delay : %(delay)d,
            minLength : %(minlength)s,
            source : %(source)s
        '''  % {
               'delay' : self.delay,
               'minlength' : self.minLength,
               'source' : source
        }

    elif isinstance(self.source, str):
        options = u'''
            delay : %(delay)d,
            minLength : %(minlength)s,
            source : function (request, response) {
                if ($(this).data('xhr')) {
                    $(this).data('xhr').abort();
                }
                $(this).data('xhr', $.ajax({
                    url : "%(source_url)s",
                    dataType : "json",
                    data : {term : request.term},
                    beforeSend : function(xhr, settings) {
                        $('#%(input_id)s').removeAttr('itemid');
                    },
                    success : function(data) {
                        if (data != 'CACHE_MISS') {
                            response($.map(data, function(item) {
                                return {
                                    label : item[1],
                                    value: item[1],
                                    real_value : item[0]
                                };
                            }));
                        }
                    },
                }))
            },
            select : function (e, ui) {
                $('#%(input_id)s').attr('itemid', ui.item.real_value);
                $('#%(input_id)s').val(ui.item.label);
            }
        ''' % {
               'delay' : self.delay,
               'minlength' : self.delay,
               'source_url' : self.source,
               'input_id' : final_attrs['id'],
        }
    if not self.attrs.has_key('id'):
        final_attrs['id'] = 'id_%s' % name    

    return mark_safe(u''' 
        <input type="text" %(attrs)s/>
        <script type="text/javascript">
            $("#%(input_id)s").autocomplete({
               %(options)s 
            });
        </script>
    ''' % {
           'attrs' : flatatt(final_attrs),
           'options' :  options, 
           'input_id' : final_attrs['id']
    })

Tip: If I write some text without selecting it from the autocomplete, it still fails.

Another tip: If I set the field as optional it arrives to the view empty.

What should I do to make this work when I submit the form??? I have spent hours trying to
make this work. How can I make the form to recognise that I have allready filled that field?

Here is the code of the form:

test = forms.CharField(label = "autotest", widget = AutocompleteTextInputWidget('/myjsonservice'))

This is the rendered html:

<input type="text"  autocomplete="off" id="id_test"/>
        <script type="text/javascript">
            $("#id_test").autocomplete({

            delay : 0,
            minLength : 0,
            source : function (request, response) {
                if ($(this).data('xhr')) {
                    $(this).data('xhr').abort();
                }
                $(this).data('xhr', $.ajax({
                    url : "/myjsonservice",
                    dataType : "json",
                    data : {term : request.term},
                    beforeSend : function(xhr, settings) {
                        $('#id_test').removeAttr('itemid');
                    },
                    success : function(data) {
                        if (data != 'CACHE_MISS') {
                            response($.map(data, function(item) {
                                return {
                                    label : item[1],
                                    value: item[1],
                                    real_value : item[0]
                                };
                            }));
                        }
                    },
                }))
            },
            select : function (e, ui) {
                $('#id_test').attr('itemid', ui.item.real_value);
                $('#id_test').val(ui.item.label);
            }

            });
        </script>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T12:13:57+00:00Added an answer on June 8, 2026 at 12:13 pm

    Finally found the answer, the problem was that the “name” attribute wasn’t rendered. Hence, the field could’t get to the view as part of the request.

    The final code of the autocomplete widget ended up like this:

    class AutocompleteTextInputWidget (forms.TextInput):
    
        def media(self):
            js = ("/js/autocomplete.js", "pepe.js")
    
        def __init__(self, source, options={}, attrs={}):
            self.options = None
            self.attrs = {'autocomplete': 'off'}
            self.source = source
            self.minLength = 1
            self.delay = 0
            if len(options) > 0:
                self.options = JSONEncoder().encode(options)
    
            self.attrs.update(attrs)
    
        def render(self, name, value=None, attrs=None):
            final_attrs = self.build_attrs(attrs)       
            options = ''
    
            if value:
                final_attrs['value'] = escape(value)
    
            if isinstance(self.source, list) or isinstance(self.source, tuple):
                # Crea un Json con las opciones.
                source = '[' 
                for i in range(0, len(self.source)):
                    if i > 0:
                        source += ', '
                    source += '"' + self.source[i] + '"'
                source += ']'
    
                options = u'''
                    delay : %(delay)d,
                    minLength : %(minlength)s,
                    source : %(source)s
                '''  % {
                       'delay' : self.delay,
                       'minlength' : self.minLength,
                       'source' : source
                }
    
            elif isinstance(self.source, str):
                options = u'''
                    delay : %(delay)d,
                    minLength : %(minlength)s,
                    source : function (request, response) {
                        if ($(this).data('xhr')) {
                            $(this).data('xhr').abort();
                        }
                        $(this).data('xhr', $.ajax({
                            url : "%(source_url)s",
                            dataType : "json",
                            data : {term : request.term},
                            beforeSend : function(xhr, settings) {
                                $('#%(input_id)s').removeAttr('itemid');
                            },
                            success : function(data) {
                                if (data != 'CACHE_MISS') {
                                    response($.map(data, function(item) {
                                        return {
                                            label : item[1],
                                            value: item[1],
                                            real_value : item[0]
                                        };
                                    }));
                                }
                            },
                        }))
                    },
                    select : function (e, ui) {
                        $('#%(input_id)s').attr('itemid', ui.item.real_value);
                        $('#%(input_id)s').val(ui.item.label);
                    }
                ''' % {
                       'delay' : self.delay,
                       'minlength' : self.delay,
                       'source_url' : self.source,
                       'input_id' : final_attrs['id'],
                }
            if not self.attrs.has_key('id'):
                final_attrs['id'] = 'id_%s' % name    
    
            return mark_safe(u''' 
                <input type="text" name="%(name)s" %(attrs)s/>
                <script type="text/javascript">
                    $("#%(input_id)s").autocomplete({
                       %(options)s 
                    });
                </script>
            ''' % {
                   'attrs' : flatatt(final_attrs),
                   'options' :  options, 
                   'input_id' : final_attrs['id'],
                   'name' : name
            })
    
    1. If someone knows how to improve this messy code it would be nice.
    2. If someone knows about a nice widget documentation for django 1.4 (Other than the oficial, which sucks by the way) it would be nice too.

    Bye, good coding everyone!!!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two text boxes that I want users to fill with geolocation data
Using: Rails and jQuery I have a form with a Url textbox input in
I am using Qt 4.7. I want to: fill text (a character, e.g.'A') with
I want to write an application that will automatically detect and fill the text
I have an ImageButton that I want to fill its parent RelativeLayout container for
If you have a normal form: <form method='post' action='#'> <input type='text' name='#' /> <input
I have four email fields in a form, and I want that the user
I have a form with the following inputs: <input type=text name=products[1][rrp] class=rrp> <input type=text
I have two fields in a form <div class=form> <label class=title>{'webmasterSubmitWebsite_rss_feed_title'|lang}</label> <div class=infos><input type=text
I am using jQuery to do an autocomplete on a text field. Based on

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.