Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a certain value to anchor tag?

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?

like image 221
Alex G. Avatar asked Feb 05 '12 10:02

Alex G.


People also ask

Can we assign value to anchor tag?

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.

How do you assign a value to a tag in HTML?

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.

Can anchor tag have data attribute?

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.


2 Answers

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>
like image 171
Andrew Jackman Avatar answered Oct 11 '22 19:10

Andrew Jackman


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

like image 25
Oybek Avatar answered Oct 11 '22 20:10

Oybek