-6

I have a link like this one

<a href="site.com/register.php?mid=username&mode=bn&bid=1">

Now i need to get value of mid or bid on the basis of

site.com/register.php

in a page. and need to do in javascript. http is also there.

How to do that.

Thank you.

Racheal
  • 21
  • 1
  • 7

2 Answers2

0

Try this :

put id for anchor tag

<a id="anchor1" href="site.com/register.php?mid=username&mode=bn&bid=1">

use below javascript

<script>
 var href = document.getElementById('anchor1').href;
 //get index of ?
 var indexStart = href.indexOf('?');
 var indexLast = href.length;
 //get href from ? upto total length
 var params = href.substring(indexStart+1, indexLast);
 //get tokens with seperator as '&' and iterate it
 var paramsArray = params.split("&");
 for(var i=0;i<paramsArray.length;i++)
 {
   //get key and value pair
   var paramKeyValue = paramsArray[i];
   var keyValue = paramKeyValue.split('=');
   alert("Key="+keyValue[0]+" and value="+keyValue[1]);
 }
</script>

Demo Link

Bhushan Kawadkar
  • 27,908
  • 5
  • 34
  • 57
  • value is not coming in href. – Racheal Sep 19 '14 at 10:28
  • i am using only var href = document.getElementById("anchor1").href; alert(href); – Racheal Sep 19 '14 at 10:30
  • and console response Uncaught TypeError: Cannot read property 'href' of null .... i have provided id same id to anchor tag. – Racheal Sep 19 '14 at 10:31
  • I have missed closing bracket in for loop, now corrected. this is the demo link http://jsfiddle.net/7La9u8p8/16/ – Bhushan Kawadkar Sep 19 '14 at 10:36
  • i think var href = document.getElementById("anchor1").href; alert(href); is not use anymore as my editor dreamweaver is not supporting it also there is no alert is showing with this. – Racheal Sep 19 '14 at 10:45
  • your example is working fine if i use jquery, but i want to use with pure javascript, once i remove jquery in your code, it fail to give alert. – Racheal Sep 19 '14 at 11:00
  • Now i have done it with your code. thank you. – Racheal Sep 19 '14 at 11:23
  • actually I was not able to put javascript code as it is in jsfiddle hence added a button click event. I am glad that it is working for you :) – Bhushan Kawadkar Sep 19 '14 at 11:27
-1
var Links = document.getElementsByTagName('a');

var Values = {}; 

for(var i = 0; i < Links.length; i++) { 
    if(Links[i].href.toString().indexOf('site.com/register.php') != -1) {

        var Str = Links[i].href.toString();
        var Arr = Str.split('?');
        Arr[1] = Arr[1] || '';

        var Params = Arr[1].split('&');
        for(var i = 0; i < Params.length; i++) {
            var Value = Params[i].split('=');
            Values[Value[0]] = Value[1] || null;
        }
        break;
    }
}

console.log(Values);
John V
  • 873
  • 6
  • 12