Search code examples
jqueryurlhrefparameter-passingcolorbox

jQuery colorbox - get url parameter from clicked link


I am using Colorbox to load a contact form within an iframe.

However, I want the Colorbox url to be different than the html one, to serve up a different contact page for JS and non-JS users.

I do need to get the url parameter from the exact clicked link though.

HTML Code:

<a href="contact?id=XX" class="enquiryForm">

Colorbox code:

$(document).ready(function(){

$('.enquiryForm').colorbox({height:600, width:800, iframe:true, href: 'colorboxcontact?id=XX'});

});

Where 'contact' is the non-JS page and 'colorboxcontact' is the page to be loaded in the Colorbox iframe.

How can I extract the url parameter from the clicked link, and then add it to the 'colorboxcontact' href value in my jQuery call?

* EDIT *

Ok I've arrived at the following but still don't have it working. Can anyone point out where I am going wrong?

$('.enquiryForm').colorbox({
    height:600, 
    width:800, 
    iframe:true, 
      href: $('.enquiryForm').each(function() {
        newhref = 'colorboxcontact' + $(this).attr('href').split("?")[3];
        $(this).attr('href', newhref);
    });
  });

Solution

  • To get specific query string info for url string you need this function found at:

    How can I get query string values in JavaScript?

    slightly modified:

    function getParameterByName(url, name)
    {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec(url);
      if( results == null )
        return "";
      else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    

    so then you will end up with something like this:

    $('.dialog-open').each(function() {
       $(this).colorbox({
         height: 600, 
         width: 800, 
         iframe: true, 
         href: "contact?id=" + getParameterByName($(this).attr("href"), "id")
       });
    });