Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parameter values from href in jquery

Tags:

jquery

href

Script

 <a href="#?cat=MT&typ=1" data-reveal-id="reveal_popup" onclick="pop();" data-closeonbackgroundclick="false" data-dismissmodalclass="close-reveal-modal">due today</a>
 <a href="#?cat=MT&typ=2" data-reveal-id="reveal_popup" onclick="pop();" data-closeonbackgroundclick="false" data-dismissmodalclass="close-reveal-modal">due in 2 days</a>

 <div id="reveal_popup" class="reveal-modal">
 <div id="popup"></div>
 <a class="close-reveal-modal">&#215;</a>
 </div>

function pop() {

 var cat=**value of cat parameter in href**
 var type=**value of typ parameter in href**

 $.ajax({
       type:'post',
       url:site_url()+'/event/deleteEventSingle',
       data:{'cat':cat,'type':typ},
        async:false,
         success:function(result){}
        });
}

In this when the user clicks a href same popup appears with different data. there are more than 10 hrefs actually and i am trying to show a calender with user inputted data in the popup. This depends on two parameters cat and typ as shown in href.

Requirement

Every href has its own cat and typ values. When a href is clicked I want the cat and typ values of the clicked href to be get using jquery so that i can pass these variables in ajax.

var cat=**value of cat parameter in href**
var type=**value of typ parameter in href**

Tried

How to get the parameters of an href attribute of a link from the click event object

like image 394
Avinash Avatar asked Apr 03 '13 06:04

Avinash


2 Answers

You can do as soeme thing as below

$('a').bind('click',function(){
    var url = ($(this).attr('href'));
    var cat = getURLParameter(url, 'cat');
    var typ = getURLParameter(url, 'typ');
    //calling the ajax function
    pop(cat, typ)
});


function getURLParameter(url, name) {
    return (RegExp(name + '=' + '(.+?)(&|$)').exec(url)||[,null])[1];
}

function pop(cat, typ) {

    $.ajax({
       type:'post',
       url:site_url()+'/event/deleteEventSingle',
       data:{'cat':cat,'type':typ},
        async:false,
         success:function(result){}
    });
}

Check out the the example at Live fiddle http://jsfiddle.net/mayooresan/aY9vy/

like image 152
Jay Mayu Avatar answered Oct 30 '22 05:10

Jay Mayu


Try this :

function getUrlParams(url) {
    var params = {};
    url.substring(1).replace(/[?&]+([^=&]+)=([^&]*)/gi,
            function (str, key, value) {
                 params[key] = value;
            });
    return params;
}

Usage:

function pop(e) {
     var url = $(e.target).attr("href");
     var params = getUrlParams(url); 

     var cat= params["cat"];
     var type= params["typ"];

     alert(cat);
     alert(type);    
}

Working Fiddle

like image 23
Gaurav Avatar answered Oct 30 '22 04:10

Gaurav