I have the following code
<a href="" (set value 1)>Inside Link which sets a value</a>
<script>
$(a).click(function() {
i=value of a tag;
$('#square').animate({'left': i * 360});
});
</script>
And i want to add a value attribute to an anchor tag. How to do it?
You need to use the href attribute to link to another page. The value of the href attribute is usually a URL pointing to a web page (like the one above). You can also link another HTML element or a protocol (for example, sending email), and you can execute JavaScript using the href attribute.
The value attribute specifies the value of an <input> element. The value attribute is used differently for different input types: For "button", "reset", and "submit" - it defines the text on the button. For "text", "password", and "hidden" - it defines the initial (default) value of the input field.
Using Data Attributes With jQuery There are a few ways we can get the data from the element using jQuery. Let's look at some of those. If we had an anchor tag, like the one above, that had a data attribute of data-info then we can access that data in the same way that we would get any other attribute value.
If you want to add a random attribute for a value, you can use data attributes:
<a href="#" data-value="1">Text</a>
<script type="text/javascript">
$("a").click(function(){
i=$(this).data("value");
$('#square').animate({'left': i * 360});
});
</script>
If you are using HTML5 you can use the data-
technique.
<a id="target" href="http://foo.bar" data-custom-value="1">Text</a>
$("#target").click(function() {
var value = $(this).data("custom-value");
// do other stuff.
});
EDIT
Usage of .data
instead of .attr
is more appropriate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With