0

I am using jQuery $.GET to scrape the search results from a remote server application and I want to have the links that are returned trigger another jquery $.GET request once they are clicked.

In the example below I am simply trying to prevent the link from opening the page and even the event.preventDefault() method is failing.

The problem is that I neither the .click() or .on("click") event handlers are firing in the example page.

Granted I am having to use CORS extension to develop this locally in Chrome but I couldn't find where that would prevent the .click events.

I've also tried using $.POST as well with no successs.

I've been at this for a bit and have googled quite a bit looking for a reasonable explanation as to why this isn't happening.

search.html

<form action="search.html" method = "post" id="searchForm">
<input type="input" name="q" id="q" />
<input type="submit" value="Search K-Tube" id="submitForm" />

</form>

<pre id="response"></pre>

 <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
  <script src="js/ktube.js"></script>
   <script src="js/common.js"></script>

ktube.js

 $("document").ready(function () {

 $('a [id^="tubeLink"]').on("click", function (event) {
   event.preventDefault();

 });

  $("#searchForm").submit( function (event) {
    event.preventDefault();

    var q = $("#q").val();

    if (q != "") {
       $.get("http://ktube.kellerisd.net/education-center?search=" + q + "&global_search=true", function(data) {
                 var count=0;
                var thumbs = $(data).find(".thumbDescription h5"); //Finds the Video Thumbnails Titles


                var output = "<h2>Results</h2><ul>";

                $(thumbs).each(function(index, value){

                var link = $(this).find("a").attr("target", "_blank"); //Finds the links and opens them in new browser window
                link = $(link).attr("href", "http://ktube.kellerisd.net" + (link).attr("href")); // Creates an absolute URL for Video on Ktube
                link = $(link).attr("id", "tubeLink" + index);

                output += "<li>"+ $(this).html(); +"</li>";
                count++;
                });

                output += "</ul><br />Total Results: " + count;


                $("#response").html(output);

        });
   }else {
    alert("Please enter a search term");
   }



  });


});

1 Answers1

1

Use this:

 $("#response").on("click",'a [id^="tubeLink"]', function (event) {
   event.preventDefault();

 });

Element to witch you add click handler must be present in dom, when you are adding it.

Beri
  • 11,470
  • 4
  • 35
  • 57
  • That did occur to me, however, it still doesn't seem prevent the link from opening. I've tried in and outside of the $("document".ready() block – Keller_District Nov 07 '14 at 15:51
  • I had to restart Chrome for the dialogs to reset. Not sure why but it was a browser issue on top of the the answer provided by @Beri – Keller_District Nov 07 '14 at 16:18