0

I would have thought this is fairly classic, but I haven't found an answer.

I have a form which links to a MySQL (actually MariaDB) database table, contacts. Part of the jQuery.ready() function populates, by AJAX, a drop-down list (i.e. <select id="drop_box" /> for example) with options, which are all the surnames + first names in the contacts table, with value = ID field from the record. Just to clarify, the injected code contains <select> as well as all the options.

Then when the user clicks on/selects one of these names I want the value (ID field) of the option to be sent to a JS/jQuery function, perhaps defined in the <head> tags. The idea would then be another AJAX call to fill various other boxes and tables and things on the page with all the other details plucked from the contacts table.

But how to get either

  1. an existing $("#drop_box").change() function to "see" and respond to events in the injected <select> objet or
  2. if injecting the change() functionality, how to get the latter to call an existing function on the page.

It strikes me as bad practice to inject all the response code as a return AJAX call, and anyway I'd just like to know how injected JS code can be made to interact with JS code already on the page.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
mike rodent
  • 14,126
  • 11
  • 103
  • 157
  • I think what you want is to load the select and options via ajax and then use jquery on binding (http://api.jquery.com/on/) to bind the change event and fire whatever javascript you'd like – Geoff Jul 28 '14 at 15:45

1 Answers1

1

Use jQuery's .on method as detailed here. Then your event will apply not only to any matching elements when it is defined but also matching elements that are added in the future via AJAX.

  • The crucial thing here being that you can define the event once in your page and not have to inject JavaScript code along with your `select`. –  Jul 28 '14 at 15:46
  • looks like it was a dupe... but thanks anyway – mike rodent Jul 28 '14 at 15:57