Aniket Singh
Aniket Singh

Reputation: 877

how to invoke a jquery plugin

I have a jquery autosuggest plugin

This is how plugin is implemented on the input field

var options = {
        script:"ajax/college.php?json=true&",
        varname:"college",
        json:true,
        callback: function (obj) { document.getElementById('college').value = obj.id; }
    };

    var as_json = new AutoSuggest('college', options);

this is how input field is appended to the page

 $('input[type=radio][name=career]').change(function() {
   if (this.value == '1') {
      $(".tp").html('<input type="text" class="form-control input-lg" name="college" id="college" placeholder="College name">');
     }
  });

but after appending plugin doesn't work on that input & if i just write the input field non dynamically then it works

<input type="text" class="form-control input-lg" name="college"
id="college" placeholder="College name">

Upvotes: 0

Views: 78

Answers (1)

andreivictor
andreivictor

Reputation: 8461

The plugin doesn't work because at the moment it is initialized, the input element with the id collegedoes not exist in the DOM.

So, you need the initialize AutoSuggest script only after that input is inserted into the page.

Try the following code:

$('input[name=career]').change(function() {
    if (this.value == '1') {

        // check if autosuggest has not already been initialized
        if (typeof as_json === 'undefined') {

           // input element is inserted into the page
           $(".tp").html('<input type="text" class="form-control input-lg" name="college" id="college" placeholder="College name">');

           // initialize autosuggest here
           var as_json = new bsn.AutoSuggest('college', options);
       }

    }

});

Fiddle here: https://jsfiddle.net/Lhdcgg3o/.

Upvotes: 1

Related Questions