简体   繁体   中英

how to empty textbox if data entered not in autocomplete list

I have a textbox in education form that shows autocomplete list of college names from college model.What i want to do is to prevent users from adding new entries ie if college name is not in the autocompleted list user cannot add new name but i am not able to do this.If user types name that is not in autocomplete list textbox should be cleared

Following is my education/form,html.haml code:

= f.label :college_id, "College<em>*</em><small>college name</small>".html_safe
= f.text_field :college_id
:javascript
$(document).ready(function() {   
    var a = ["abcd","abc"];
    $('#education_college_id').focus().autocomplete(#{colleges_names_arr});
}); 

In my application_helper i have written following code for autocomplete.

def colleges_names_arr(colleges=[])
req_colleges = College.all
colleges_names = req_colleges.collect{|col|col.full_name}.to_json
end

What should i write to prevent users from adding new data and empty textbox.

Think you need the Combobox example not the default functionality for JQuery-UI Autocomplete.

http://jqueryui.com/demos/autocomplete/#combobox

Alot more complicated than the simple text box because it includes some checking to make sure that the input text includes a value from the provided list (or replaces the text with a blank).

Or you could check the params on submission (a good idea to do this anyway) to make sure that the param value is inlcuded in the college list.

One other point is that you don't seem to be passing the College ids to the select just the College names - getting autocomplete to return both the id and name of the college will be a pain (maybe look at https://github.com/crowdint/rails3-jquery-autocomplete ).

In the Update and Create actions you'll have to take the provided College names and look up via College.find_by_name() before saving the record. Probably by using a text_field_tag college_name to return the params[:college_name] (this will not be dependent on the rest of the Education form) then something like

_form.html.haml

= label_tag :college_name, "College<em>*</em><small>college name</small>".html_safe
= text_field_tag :college_name
:javascript
$(document).ready(function() {   
    var a = ["abcd","abc"];
    $('#college_name').focus().autocomplete(#{colleges_names_arr});
}); 

education_controller.rb

*in the Create and Update actions

education = Education.create!(params)
college = College.find_by_name(params[:college_name])
if college
  education.college = college
end

There's definitely a cleaner way of doing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM