How to trigger a click on a link using jQuery
Home » BLOG » jQuery » How to trigger a click on a link using jQuery

How to trigger a click on a link using jQuery

category:  jQuery

Today I am working on some small tasks. It should not take long. But I stuck on one issue for a while. Here is what I am trying to do.


I have the page link list that is generated by the pagination_link from WordPress. The code looks like this.

$big = 999999999;
$url = str_replace($big, '%#%', html_entity_decode(get_pagenum_link($big)));     
$pagination_dropdown_args = array(
    'base' => $url,
    'format' => '?paged=%#%',
    'total' => $total_pages,
    'current' => $paged,
    'show_all' => true,
    'end_size' => 1,
    'mid_size' => 2,
    'prev_next' => false,
    'type' => 'list',  // 3 types you can use which are plain, array, list
    'add_args' => false,
    'before_page_number' => '<span>',  // you must add any element inside the a tag, so you can use the trigger on click event for a tag.
    'after_page_number' => '</span>'
$paginate_dropdown_links = paginate_links($pagination_dropdown_args);

The result of paginate_links looks like this:

<ul class="page-numbers">
    <li><a class="page-numbers" href=""><span>Google</span></a></li>
    <li><a class="page-numbers" href=""><span>Youtube</span></a></li>

Next, I want the users can choose the site from the select box. After they choose the site from the select box, jQuery will trigger the link from the ul list above. Here are the select box look likes.

<select id="select-box">
    <option value="0">Google</option>        
    <option value="1">Youtube</option>        

Now, I need the jQuery to do the work.

$(document).ready(function () {
    $("#select_box").change(function() {
        var selected_page =  $("#select_box :selected").val();                
        // trigger the page link
        // # important note: 
        // you must add any element inside the a tag in order to trigger the click event for a tag via jquery
        // In this case, I add a span tag.
        $(" > li:eq("+selected_page)+")>").find("span").trigger("click");             

That’s it.

For the jQuery, trigger the text inside the a tag, it won’t do anything. jQuery won’t recognize it. That’s why I add <span> inside the a tag. Then uses find() to find the span tag and then trigger the click event. However, in javascript, you don’t have this kind of issue.