I’m (very slowly) making a website, and I’m creating a search engine for the database, which is essential to organize the dependencies during data entry.
Anyway, what I would like is to type a few keywords into a box, have a menu pop up with various search results, and have the box fill with the ID number of the selected entry when it’s clicked.
Currently, I have a document called search.php which fills a div called search-output using xmlhttp.open() and the innerhtml property. Everything is working perfectly except for filling the original search box with the ID number when clicking.
My first attempt was to add an onclick event to each entry in the output from search.php. Unfortunately, I found that javascript inserted into innerhtml is not run for security reasons. I’ve been Googling for hours but haven’t been able to find a solution.
How can I get the original search text box to fill with the correct ID when I click it? Is what I’m doing a good setup for the results I desire, or is there a better way to integrate search features into data entry?
3
Assuming I got what you mean correctly, The solution would be to have a single event handler on the div
which is getting populated with the results, and use the Event
object passed to the event handler to determine exactly which object was hit:
<input type="text" id="search" name="search">
<div id="search-popup"></div> <!-- This will be populated with partial results -->
And in the JavaScript, this JavaScript is not inserted into the page, but is part of it:
var searchPopup = document.getElementById("search-popup");
searchPopup.onclick = function(event) {
var actualClickedElement = event.target; //Magic is here
//Handle your event, probably by changing searchInput.value
};
Now you can handle things with actualClickedElement inside the handler function. This also provides a nice performance boost when things get larger, since you only ever have one handler.
Read up on event delegation @ MDN.
12