0

Please help, I need to select the "10" on this link using jquery where it says id=10 and also the "do" where it says type=do

<a class="myClass" href="/local/web/do.php?type=d0&id=10">link</a>

I tried jQuery(this).attr('href'); but that returns all the link address, I need to set each as a variable.

I want something like var id = "the selector that selects only the id value" var type = "the selector that selects only the type value"

Thanks

Kingsley
  • 9
  • 2
  • What link? Can you show an example? –  Feb 16 '19 at 05:23
  • 1
    Possible duplicate of [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – andrew Feb 16 '19 at 05:27
  • @Kingsley check my answer – p u Feb 16 '19 at 05:30
  • i guess this will help https://github.com/kevincox/url.js source https://stackoverflow.com/a/15753120/7887883 – Pavan Kumar T S Feb 16 '19 at 05:37
  • https://stackoverflow.com/questions/2090551/parse-query-string-in-javascript may help – Vipin Kumar Soni Feb 16 '19 at 05:44
  • Welcome to Stack Overflow. Do you want to get the value of id, type on click of the link? Or do you want to get the ID on page load? Are there multiple such links with same class ".myClass" on the page? Can you post code snippet of what have you tried so far? https://stackoverflow.com/help/mcve – codingbbq Feb 16 '19 at 06:00
  • Yes, that's exactly what I want, I have a loop that displays multiple posts with different ids and types, so I just want to get the id of the link and type when clicked so I could send as variable to another page using jquery ajax function. – Kingsley Feb 16 '19 at 08:18

2 Answers2

1
function getQueryVariable(query, variable) {
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}

$(".myClass").on("click", function(event){
    event.preventDefault();
    var href = $(this).attr('href');
    var query = href.split('?');
    var vars = query[1];

    console.log(getQueryVariable(vars, 'type'));
    console.log(getQueryVariable(vars, 'id'));
});

Try this, reference: Parse query string in JavaScript

Vipin Kumar Soni
  • 826
  • 10
  • 18
-1

Is that what you are looking for??

I've splited id from clicked link

function doalert(obj) {
  var type = obj.getAttribute("href").split('type=')[1];

  console.log("id--", obj.getAttribute("href").split('id=')[1], "type--", type.split("&")[0]);
}
<a class="myClass" href="/local/web/do.php?type=d0&id=10" onclick="doalert(this)">link</a>
p u
  • 1,395
  • 1
  • 17
  • 30
  • I believe this would just get the `id` parameter, but he asked to extract both `id` and `type` – andrew Feb 16 '19 at 05:31