toby
toby

Reputation: 3

How to get value from input and submit it with jQuery?

I want to get the value of an input without submitting it/reloading the page, and then use this to make a get request to an API. Here is the html:

<form name="music_title" id="search_it">
   <input name="song_name" id="search_song" placeholder="Enter song to add" onsubmit="return searchSg()"/>
</form>

Here is the javascript I've written to do this

searchSg = function(){
    oForm = documents.forms[0]
    SC.get("/tracks", {q: oForm.elements["song_name"].value , limit: 20}, function(tracks){
        $(tracks).each(function(index, track) {
            //do stuff with track info
        });
    });
}
$("#search_song").submit(searchSg() { return false; });

But none of this is getting executed the form is still being submitted. I've tried using an ajax call but that also doesn't get executed at all. I've made sure that my path to static folder is working fine and I've gotten other functions to work fine. It seems like whenever I try to make an ajax request, the javascript just doesn't work and now I can't get the form to get the data this way either.

Upvotes: 0

Views: 44

Answers (1)

JOSEFtw
JOSEFtw

Reputation: 10071

Try this:

$("#search_it").submit(function(ev){
    //Do stuff here
    var songName = $('#search_song').val();

    $.get('/tracks', {q : songName, limit: 20}, function(tracks){
       //Do something with the response(tracks) here
    });
   //You can call ev.preventDefault() but return false will do that for you..
   return false;
});

Upvotes: 1

Related Questions