-5

I have this <a> href attribute

<a id="cancel" value="<?php echo $subID;?>" href="#">Cancel</a>

and I need to get its value ($subID) and assign it to a JavaScript variable. How can I do that?

user5718409
  • 92
  • 3
  • 9

4 Answers4

0

You could add the value as a custom data-attribute

HTML:

<a id="cancel" data-value="<?php echo $subID;?>" href="#">Cancel</a>

And then retrieve the value like this

JS:

$('#cancel').data('value');
Rob Howells
  • 496
  • 3
  • 9
0

You don't need jQuery. Plain JavaScript is easy enough:

Traditional:

var value = document.getElementById('cancel').getAttribute('value');
console.log(value);
<a id="cancel" value="Hello world!" href="#">Cancel</a>

Using a CSS selector:

var value = document.querySelector('#cancel').getAttribute('value');

Using jQuery

var value = $('#cancel').attr('value');

Although this works (at least in Chrome), a link doesn't have a value attribute so this HTML is invalid. If you use HTML5 (which you probably will), you can make it valid by naming the attribute 'data-value'. Attributes with the 'data-' prefix are allowed for this purpose.

There are other solutions too, but since they are out of scope here, please check Can I add custom attributes to HTML tags.

Community
  • 1
  • 1
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
0

Instead of using value, you should use data-value="<?php echo $subID;?>"

then you can get the value like this

var myVal = $('#cancel').data("value");
Hugo S. Mendes
  • 1,076
  • 11
  • 23
0

You have two ways (and more) to solve this

With jQuery:

var x= $('#cancel').val();

with JavaScript:

var x= document.getElementById("cancel").value;
João Pedro
  • 546
  • 1
  • 5
  • 19