autocomplete works only sometimes
First jquery project for me and first time doing anything with JS in a long time, so be gentle. :)
So first let me tell you what I am trying to accomplish. I have a radio button, and depending on what value is selected I want to change the autocomplete source for a text box. So if the user selects option 1 on the radio button then get autocomplete list 1 and if they select option 2 on the radio button they should get autocomplete list 2.
If I assign an autocomplete at the top level:
- $('#search-input').autocomplete({
- source: function (request, response) {
- var SearchType = $("input[name='SearchType']").val();
- console.log(SearchType);
- $.getJSON("https://rxnav.nlm.nih.gov/REST/spellingsuggestions.json?name=" + request.term, function (data) {
- response($.map(data.suggestionGroup.suggestionList.suggestion, function (value, key) {
- return {
- label: value,
- value: value
- };
- }));
- });
- },
- minLength: 3,
- delay: 300
- });
That works just fine. If I try and define the autocomplete inside the change() of the radio button then I get a typeerror of "undefined is not a function" on line of the code below:
- $("input[name='SearchType']").change(function(){
- var placeholder=$(this).val();
- $('#search-input').attr('placeholder',placeholder);
- //only populate drugs
- console.log(placeholder);
- console.log($('#search-input').val());
- if(placeholder == 'Drug'){
- $('#search-input').autocomplete({
- source: function (request, response) {
- $.getJSON("https://rxnav.nlm.nih.gov/REST/spellingsuggestions.json?name=" + request.term, function (data) {
- response($.map(data.suggestionGroup.suggestionList.suggestion, function (value, key) {
- return {
- label: value,
- value: value
- };
- }));
- });
- },
- minLength: 3,
- delay: 300
- });
- }else if (placeholder == 'Event'){
- $('#search-input').autocomplete = null;
- $('#search-input').autocomplete({
- source: function (request, response) {
- $.post("http://api.ohdsi.org/WebAPI/CS1/vocabulary/search", { 'QUERY':request.term, 'VOCABULARY_ID':'SNOMED','DOMAIN_ID':'Condition'}, function (data) {
- console.log(data);
- response($.map(data, function (value, key) {
- return {
- label: value,
- value: value
- };
- }));
- },'json');
- },
- minLength: 3,
- delay: 300
- });
- }
- });
Most of the issues I've seen with this are with the jquery.js file not being loaded properly, or being loaded twice etc which I know isn't the case here because it works when I just assign the autocomplete() not in another form handle's change() but just at top-level.
Any help appreicated, thanks in advance!