-1

So, for an online poll I'm displaying a list of services. I also want my users to be able to search this list. I wrote a jQuery script that stores the clicked service for use later on. However, when I search for a service and then click it, the jQuery script doesn't respond. I can't, for the love of god, figure out why it doesn't work.

PHP

$sql = "SELECT ServiceAddress,ServiceID,ServiceIcon FROM Services WHERE ServiceName LIKE '%" . $_POST['data'] . "%'";
$query = mysql_query($sql);
$num_rows = mysql_num_rows($query);
if ($_POST['data'] == "") {
    echo '<table></table>';
} else {
    if ($num_rows > 0) {
            echo '<ul>';
            while($row = mysql_fetch_object($query)) {
                echo '<li>
                <a class="serviceIcon" id="serviceID' . $row->ServiceID . '">
                <img id="' . $row->ServiceID . '" src="data:image/png;base64,' . base64_encode( $row->ServiceIcon ) . '" alt=\"\" height=\"80%\" /></a></li>';
            };
            echo '</ul>';            
    } else {
        ?>
        <table>
            <tr>
                <td>Unfortunately, no results have been found. You can refine your search.</td>
            </tr>
        </table>
       <?php
    };
};
mysql_free_result($query);
exit();

jQuery

$( "#searcher" ).keyup(function() {
        var formData = {data: document.getElementById('searcher').value};
        $.ajax({
            type: "POST",
            url: "Including/php/searcher.php",
            data: formData,
            success: function(data) {
                document.getElementById('icons').innerHTML = data;
                document.getElementById('icons').style.display = "block";
            }
         });
});
$('.serviceIcon').click(function(event) {
    var id = $(this).attr('id');
    $.variablesnamespace.selectedID = id.replace('serviceID', '');
});
  • Can you check the error console for the error log then paste it here. – Arriane zafe Apr 09 '14 at 16:57
  • possible duplicate of [In jQuery, how to attach events to dynamic html elements?](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – epascarello Apr 09 '14 at 17:07

2 Answers2

1

Click() does not work with dynamically added elements, use on:

$('.serviceIcon').on('click', function(event) {
    var id = $(this).attr('id');
    $.variablesnamespace.selectedID = id.replace('serviceID', '');
});
Steve
  • 20,703
  • 5
  • 41
  • 67
0

you need to delegate or use on because you add the the html to the DOM programmatically.

$(function(){

    $('.serviceIcon').on('click',function(event) {
        var id = $(this).attr('id');
        $.variablesnamespace.selectedID = id.replace('serviceID', '');
    });

})
Arriane zafe
  • 131
  • 6