Mushfiqul Tuhin
Mushfiqul Tuhin

Reputation: 676

How to redirect to another link with javascript in a wordpress site?

I have a wordpress geo theme driven website where user can search for events. When I start to write anything in the text box for searching event, then a auto completer suggestion comes in (which is a plugin). After clicking any suggestion it fills the textbox, and submits a form to index page.

But I need, after clicking the suggestion it will fill the text box(which is currently OK) and redirect the page to another link to same site like this: http://sitename.com/events/text-comes-from-text-box.
"text-comes-from-text-box" is the text which will come form the text box after clicking the suggestion.

Suggestions come from a plugin and suggestions come to this page "review_searchform.php". Suggestions come as <div id='ac_results'><ul><li>. I am trying to find out,if I click on the <li> which is coming from the plugins is responding. For do that I used this code in review_searchform.php this page, but it's not working. My code is below,

<script type="text/javascript">

    jQuery("#ac_results ul li").click(function() {
    alert("test 2");

});

If it would work, then I would add redirect code here. I think to solve this problem, it does not need PHP or WordPress functions. It only needs Javascript/jQuery.

Upvotes: 1

Views: 17123

Answers (3)

Ahmet Can G&#252;ven
Ahmet Can G&#252;ven

Reputation: 5462

Ok lets say your suggestion box is a div with class="suggestion".

We want to redirect our page to this suggestions text as address.

Example of your suggestion html

<div class="suggestion">Air Control Service</div>

After clicking this link your visitor must go to this address right? :

http://sitename.com/events/Air-Control-Service

Ok then lets write our jquery code.

$(document).ready(function(){ //Take care to conflict issue
  $(".suggestion").on("click", function(){ //When visitor clicks your suggestion
    var eventText = $(this).text(); //Get text from suggestion 
    eventText = eventText.replace(" ","-"); //Replace "-" for " "
    var base = "http://sitename.com/events/"; //Set your base address
    window.location.href = base + eventText; //Redirect your visitor
  });
});

That is all, I hope this will be helpfull.

Edit: Changed my script to .on() version. Now ajax returns also included in events.

Upvotes: 4

eosterberg
eosterberg

Reputation: 1452

$("#ac_results ul li").each(function () {
    $(this).click(function () {
        window.location = $(this).text();
    });
});

Upvotes: 2

Rikky
Rikky

Reputation: 515

window.location = your_url will make your browser redirect immediately

Upvotes: 3

Related Questions