Search code examples
jqueryhref

Get parameter values from href in jquery


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


Solution

  • 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/