Can anyone help me make the search bar work as I now have the JS prompt?

129 views Asked by At

I have created a small program that pulls from the YouTube API which allows you to search for a random video for whatever title you enter when prompted. My goal is to have this work like a search engine. I would like to make my search bar the input instead of the alert prompt window. Similarly, I would then also like to make the "Find" button act as the "Ok" button on the prompt alert window when you run the program with javascript in jsbin. Can someone point me in the proper direction to accomplish this? Here is the jsbin. I am assuming that I can just use some sort of OnClick function for the button, but not totally sure how to implement that and what I would call it on. Thank you!

PS. I'm certain you already know this, but just in case... Make sure you run the program in the jsbin with "Run with JS."

1

There are 1 answers

2
brso05 On BEST ANSWER

You can just add an onclick listener to the find button and trigger the code when someone clicks. You can get the value of the search input instead of the prompt:

Javascript:

function search()
{
    var api_key; 
    api_key = "AIzaSyDiUEkwoldcB9qgRreOsaiyu2Nlj8U-03c";

    var search_term = document.getElementById("searchterm").value;

    function onSuccess(data){
        console.log(data);
        var obj = data.id;
        console.log (data.items[0].id.videoId);

        video_url = 'http://www.youtube.com/embed/' + data.items[0].id.videoId     +'?autoplay=1'; 
        video.src = video_url;
    }

    var youtube_url = 'https://www.googleapis.com/youtube/v3/search?part=id&q=' +search_term +'&maxResults=1&key=' +api_key;

    var video_url = 'http://www.youtube.com/embed/' +"IQ1_acLEVVo"+'?autoplay=1'; 


    $.ajax({
      method:'GET',
      url: youtube_url,
      success: onSuccess
    });

}

HTML:

<button type="button" id="search" onclick="search()">Find</button>

jsbin