2

I want to be able to obtain the value of the variable view_data_id and store inside another variable called view_data_id_fk.

The last line of code doesn't seem to work on my end, so I'm wondering how I can go about doing it?

var view_data_id = val['view_data_id'];
// How to obtain the value of view_data_id?
<td><a href="datamapmain.php?view_data_id='+view_data_id+'" 
class="link">Link</a></td>
//Will be passed on to ajax file
view_data_id_fk:$('.link').val();
Vedran Maric
89410 silver badges22 bronze badges
asked Dec 23, 2018 at 8:07
1
  • jQuery method .val() only applies to form tags like input, select, etc. Commented Dec 23, 2018 at 8:15

2 Answers 2

1

You can get the value using jQuery and attr(..) method (or just standard JavaScript) and regular expressions :

jQuery:

var q = $('.link').attr('href').match(new RegExp('[?&]view_data_id=([^&#]*)'));
var view_data_id_fk = q ? q[1] : '';

Standard JavaScript:

var q = document.querySelector('.link').href.match(new RegExp('[?&]view_data_id=([^&#]*)'));
var view_data_id_fk = q ? q[1] : '';

[Edited, thanks to Alexei Levenkov]

There is a standard way to do this, with URLSearchParams api, but it has limited browser support (caniuse, MDN):

var q = new URLSearchParams(document.querySelector('.link').href).get('view_data_id');
var view_data_id_fk = q || '';
answered Dec 23, 2018 at 8:24
Sign up to request clarification or add additional context in comments.

2 Comments

RegEx is bad way to parse urls - please use stackoverflow.com/questions/901115/…
Thanks for the info, I was not aware of that.
0

Create a reusable function as below

function getUrlParam(url,name){
 var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
 var results = regex.exec(url);
 return results === null ? '' : 
 decodeURIComponent(results[1]).replace(/\+/g,'');
}

Get the href attribute value using JQuery var url = $('.link').attr('href')

var view_data_id_fk = getUrlParam(url, 'view_data_id');
answered Dec 23, 2018 at 9:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.