tags:

views:

44

answers:

2

I have an anchor like <a href="/category/post/?type=234#content">link</a>. Using a jQuery is it possible to get the value of "type" in URL and assign as a value for a hidden input type in same page without refreshing the page.

+2  A: 
$(function() {
    var val = $('a').attr('href').match(/type\=\d+/)[0].replace(/type\=/,'');
    $('input[type=hidden]').val(val);
});

example :

var href = "/category/post/?type=234#content";
var filter = href.match(/type\=\d+/)[0].replace(/type\=/,'')
console.log(filter);
Ninja Dude
but i only need the value of <b>type</b> and use it as value for hidden input type
daron
@daron updated =)
Ninja Dude
what should i do if i only need "234" but not "#content"
daron
@daron updated , just change the regular expression!!
Ninja Dude
A: 

I'd written a function to get the querystring parameters as a map a while ago:

  /**
   * Gets the query parameters of the given URI as a associative array or map
   * e.g. Given a URI http://www.level3labs.com/jaf?foo=bar&amp;baz=bazzm, will
   * give {"foo":"bar", "baz":"bazzm"}
   * @param {URI} strUri The uri with a query
   * @return Object containing query params or and empty object 
   */
  function getQueryParams(strUri)   {
     var paramMap = {};
     if(!strUri)   {
        return paramMap;
     }

     var strQuery = strUri.substring(strUri.indexOf("?"));

     if(strQuery.lastIndexOf("#") !== -1) {
        strQuery = strQuery.substring(0, strQuery.lastIndexOf("#"));
     }

     if(strQuery && strQuery.indexOf("?") === 0 && strQuery.length > 1) {
        strQuery = strQuery.substring(1);
        var paramValArr = strQuery.split("&");
        for(var i = 0, len = paramValArr.length; i < len; i++)   {
           var paramVal = paramValArr[i];
           var delimIdx = paramVal.indexOf("=");

           var param = null;
           var val = null;
           if(delimIdx >= 0) {
              param = unescape(paramVal.substring(0, delimIdx));
              val = unescape(paramVal.substring(delimIdx + 1));
           }else {
              param = unescape(paramVal);
           }
           paramMap[param] = val;
        }
     }
     return paramMap;
  }

This can be used in conjunction with the code below:

   var uri = $('a').attr('href');
   var params = getQueryParams(uri);

   $('input[type=hidden]').val(params["type"]));
naikus
what should i do if i only need "234" but not "#content"
daron
@daron Updated my answer (function code) to handle fragments. Now you will get proper name-value pairs
naikus