Jim
Jim

Reputation: 694

Automatically submit input on page open with javascript

I have this code

var file = getUrlVars()["file"];
    if(file){
            document.getElementById('search').value = file; 
    }
    function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

It reads the parameter file from url and then puts the value in the search field. The search field is ajax powered, when a user enters a letter it starts searching and outputs results. The problem is that when the scripts puts the value in the search field nothing happens, how do i make the search to fire up?

This is my search field

<input type="text" id="search" class='search_input' />

UPDATE: My Ajax search code is this

// Search
$(document).ready(function()
    {
        $(".search_input").focus();
        $(".search_input").keyup(function() 
    { 
    var search_input = $(this).val();
    var keyword= encodeURIComponent(search_input); 
    var yt_url='http://domain.com/search.php?q='+keyword;  
    $.ajax({
        type: "GET",
        url: yt_url,

        success: function(response)
    {
        $("#result").html('');
        if(response.length)
        { 
            $("#result").append(response); 
        }
        else
        {
            $("#result").html("<div id='no'>No results</div>");
        }
    }   

    }); 
    });
}   ); 

Upvotes: 0

Views: 233

Answers (1)

Alex
Alex

Reputation: 35409

Your search will only "fire" if the event that initilizes the AJAX functionality is triggered. Thus, you need to trigger the event. My wild guess is the event is bound to either:

 - keyup
 - click
 - blur

You haven't posted the relevant code, but that should be enough of an answer...


After your update

A quick solution is to initiate the keyup event on the search field:

$(".search_input").keyup(function() { ... }).keyup();

Or, you could re-factor the code:

function searchlogic() { ... };

$(".search_input").keyup(searchlogic);

searchlogic();

Upvotes: 1

Related Questions