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?
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?
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');
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.
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");
You have two ways (and more) to solve this
With jQuery:
var x= $('#cancel').val();
with JavaScript:
var x= document.getElementById("cancel").value;