Problem returning a value from clicked link - javascript

I have a set links on a page like this
<a href='' class='contact' data-index='1'>One</a>
<a href='' class='contact' data-index='2'>One</a>
<a href='' class='contact' data-index='3'>One</a>
I am trying to return the value of the data-index of each link when it is clicked but Whenever I click on each link, the data-index of the first link is always returned because jQuery will select all the links with class = 'contact' on the page.
I am trying to figure out how to select the data-index of the clicked link.
I use something like this :
var m_data = $("a#contact").attr("data-index");
I've also tried something like this :
$("a#contact").click(function() {
var data = $(this).data('index');
});
but data was undefined.
Please how do I do this? Thanks.

# is an id selector. Which should be unique. When using id-selector in jQuery, it will always return the first element, since it isn't expecting to find any more items.
Change your code
<a data-index="1" class="contact">Whatever</a>
$("a.contact").click(function() {
var data = $(this).data("index");
});
And as Eskat0n mentions, since jQuery 1.6, jQuery automatically gets data- attributes via the data() method

Since jQuery 1.6.x values of data attributes populates into data associated with element by jQuery, so if your html look like <a class="contact" data-index="5"></a> your code should work:
$("a.contact").click(function() {
var data = $(this).data('index');
// data is "5"
});
As you can see there is correction: # used to get element by id which needed to be unique. Use class intead of id for multiply link elements.

$("a.contact").each(function()
{
$(this).click(function()
{
var data = $(this).attr('data-index');
});
});

You want .index(). This fiddle indicates how it can be used if the list of links is the only list on the page and also if there are other DOM elements mixed in with the links.

Related

Accessing properties of a tag within a tag

I have an a tag as follows:
<a href="data1.html" class="list-group-item" data-toggle="collapse">
<i class="glyphicon glyphicon-folder-close"></i>Root Folder
</a>
I have a function that gets called when you click on a tag. It is as follows -
$(document).ready(function() {
$("a").hover(function(event) {
console.log(event.target.href);
});
});
I can access the properties of a tag. Example: If i want to access the href of the a onclick, I can get it by event.target.href.
I want to access the properties of the i tag that is inside the a tag (for instance, class of i tag is "glyphicon glyphicon-folder-close").
How do I achieve that?
Also, what changes do I have to make to the function, such that it is called only if a tags of class = "list-group-item" are clicked?
Thanks in advance.
I want to access the properties of the i tag that is inside the a tag
Inside any jQuery event handler, this refers to the element on which the event was triggered: therefore you can use any selector relative to that element. $(this).children('i') for example will find the contained i given your HTML; if the element might be nested more deeply you'd want .find() instead of .children().
what changes do I have to make to the function, such that it is called only if a tags of class = "list-group-item"
Change the selector you're using to attach the handler - $("a.list-group-item") instead of $("a") to limit it to items having that class.
Note also that if you want this to work on click as you describe, rather than on hover as in your sample code, you'll need to return false from the event handler (so that the regular link navigation doesn't occur).
$(document).ready(function(e) {
$("a.list-group-item").click(function() {
var myChild = $(this).children('i')
console.log(myChild.attr("class")); // for example
return false; // prevent regular navigation from occurring on click
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://example.com" class="list-group-item">
<i class="glyphicon glyphicon-folder-close"></i> Will fire handler on click
</a>
<br>
<a href="https://example.com">
<i class="glyphicon glyphicon-folder-close"></i> Will navigate normally
</a>
Since you are using jQuery, this will be very easy!
$(document).ready(function() {
$("a.list-group-item").click(function(event) {
$(this).find('i').attr('class');
});
});
To get only certain anchor tags you can use a selector, read more about them here. Then you can use the this object to find children. Use the find method in jQuery. Finally use the attr to retrieve the class.
You can rewrite your function like this:
$(document).ready(function() {
//Only use list-group-item
$("a.list-group-item").hover(function(event) {
var $attrNode = $(this).find("i");
//Now that you have the list group item it is easy to get the attribute
var attributeValue = $attrNode.attr("your-attribute");
//You can also set the attribute
$attrNode.attr("your-attribute", "attribute value");
});
});

Select the value/text of an <a> element with jquery

I got these 3 links
<a id="ajaxed" href="#" value="213">WTF</a>
<a id="ajaxed" href="#" value="213">DUDE</a>
<a id="ajaxed" href="#" value="213">SRSLY</a>
And I want to parse the value attribute. I'm using this script but it always return null.
jQuery.noConflict();
jQuery(document).ready(function ($) {
$('#ajaxed').on('click',function() {
var value = $(this).val();
alert(value);
});
});
Also I tried parse the text and it only works for the first one <a>.
The fiddle of that one:
http://jsfiddle.net/dzasusxp/18/
What am I doing wrong? It seems kinda ok for me...
IDs are has to be unique per element in a page and also .val() should only be applied on form elements. To get the value you should consider the .attr() method.
To get this working you should change your id attribute to class.
$('.ajaxed').click(function(){
var val = $(this).attr('value');
alert(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="ajaxed" href="#" value="213">WTF</a>
<a class="ajaxed" href="#" value="213">DUDE</a>
<a class="ajaxed" href="#" value="213">SRSLY</a>
The problem is, id attribute should be always uniqe in HTML.
See here.
Use a class instead the id.
See the FIDDLE
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
Id must be unique.
http://www.w3.org/TR/html401/struct/global.html#h-7.5.2
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
class = cdata-list [CS]
This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.
Change your ajaxed id to class and following code work fine.
jQuery(document).ready(function ($) {
$('.ajaxed').on('click',function() {
var value = $(this).text();
alert(value);
});
});
http://jsfiddle.net/dzasusxp/20/
$('#ajaxed') will not be returning array of 'a' tag elements. It returns the first matched element. Try to give different ID's or same class name, as below
jQuery.noConflict();
jQuery(document).ready(function ($) {
$('.ajaxed').on('click',function() {
var value = $(this).text();
alert(value);
});
});
<a class="ajaxed" href="#" value="213">WTF</a>
<a class="ajaxed" href="#" value="213">DUDE</a>
<a class="ajaxed" href="#" value="213">SRSLY</a>
See difference between id and class ID/CSS
The attribute value in an a tag is an invalid attribute. The method .value() takes focus for form fields. If you really want to use this attribute in an a tag, use the method .attr("value") instead of .value().
try $el.txt() to get el.innerText

How to change onclick attribute on html file?

I have a progress bar and want to change it's data-pro-bar-percent attribute value from 80 to 100 when I click a link.
The attribute change should be as follows:
data-pro-bar-percent="80" --> data-pro-bar-percent="100"
This is the HTML:
<a class="button" href="#">Click Link</a>
<div class="pro-bar-container color-green-sea">
<div class="pro-bar bar-100 color-turquoise" data-pro-bar-percent="30" data-pro-bar-delay="4000">
<div class="pro-bar-candy candy-ltr"></div>
</div>
</div>
Links are not buttons! Use buttons!
Use the DOM's setAttribute method to alter the data attribute. This is tricky though, you can either grab the percent element by its classname (if it shares a class name with another element, you may want to use this.children.children.setAttribute()) so grab the closest nested child you want.
Simply set the link/button element an eventListener (if it's in a form, a button acts like a submit button by default, so you may need to prevent the default action), and give it a function to change the data attribute.
<button id="myButton">Click Me</button>
var button = document.getElementById("myButton");
button.addEventListener("click",function() {
document.getElementsByClassName("pro-bar")[0].setAttribute("data-pro-bar-percent","100");
}, false);
As #rlemon commented, getElementsByClassName lacks the support that querySelector does, so you should use that instead.
document.querySelector(".pro-bar").setAttribute("data-pro-bar-percent","100");
You should use .data() instead of .attr() to get the current data value and then set it as well. Much more efficient.
http://api.jquery.com/data/
$('.button').on('click', function(){
var current = $('.pro-bar').data("pro-bar-percent");
$('.pro-bar').data("pro-bar-percent", current += 20);
});
You can use jQuery, first give an id to your link:
<a class="button" id="btnLink" href="#">Click Link</a>
Now, use this, if you directly want to change the value of data-pro-bar-percent to 100.
$("#btnLink").on("click",function(){
$(".pro-bar .bar-100 .color-turquoise").attr("data-pro-bar-percent","100");
});
If you just want to increment the value of the current bar by 20 then use this:
$("#btnLink").on("click",function(){
var targetEle = $(".pro-bar .bar-100 .color-turquoise");
var currentBar = parseInt(targetEle.attr("data-pro-bar-percent"))+20; // whatever value you want to increment with.
targetEle.attr("data-pro-bar-percent",currentBar);
});
Hope this helps

JQuery selector by data attribute when data is added dynamically?

I have a ul with several items. I populate the list dynamically after page load using jquery. As I add each list item, I also add an "itemID" to the data of that element using the jquery ".data()" function. Something like this:
var item = $('<li>My Item Name</li>');
item.data('itemID', '123ABC456');
Later, I need a selector to determine if there is any item in my item list with a specific itemID. First I tried using:
$('*[data-itemID="123ABC456"]');
This didn't work - and on further research, I discovered that this syntax only works if the data attribute was set in the DOM when the page was loaded; it doesn't work if you use the ".data" jquery method dynamically.
Next I tried:
$(':data(itemID==123ABC456)');
For some reason, this doesn't work. If I run simply $(':data(itemID)'), however, then I do get all the li elements that have an itemID in their data.
I know that the itemID attribute is set correctly, as when I call .data() on that list item I get:
Object { itemID="123ABC456"}
How can I select all elements that have an itemID of "123ABC456" in their data?
http://jsfiddle.net/w28p9/1/ <-- jsFiddle example showing differences with data-attribute & jquery.data()
jQuery.data() is different than HTML5 data-NAME attributes which you are trying to search for.
http://api.jquery.com/jQuery.data/
jQuery.data() saves inside of the jquery element (this data is hidden from plain sight).
Looking for [data-itemID] would work if inside of the actual had: <li data-itemID="12345"></li>.
To retrieve and look for the actual hidden .data() try:
// of course be more specific than just searching through all <li>'s
$('li').each(function () {
if ( $(this).data('itemID') === '123ABC456' ) {
// do whatever you wanted to do with it
}
});
Hope that helps!
Instead of
$(item).data('itemID', '123ABC456')
use
$(item).attr('data-itemID', '123ABC456')
Then you can use
$('[data-itemID=123ABC456]')
as a selector
How about putting the itemID in the DOM:
var item = $('<li itemID="'+itemid+">My Item Name</li>');

Looping an array together with a jquery hover function

I'm trying to... God, this is hard to explain.
I got an array called 'triggers' with these variables:
"#1_trigger","#2_trigger","#3_trigger"
And inside a jQuery each(), I create another variable called 'targets' that copies everything from 'triggers' and replaces all _trigger to _target. I then append the 'triggers' to anchor IDs, and 'targets' to hidden div IDs.
What I want to do, is this: When hovering a _trigger, the _target will show up. I've managed to make it work with only one variable, but not with multiple.
As I said, it's kind of hard to explain what I want to do in text, so here's a demo and my progress so far:
http://jsfiddle.net/WJWe3/6/
I've been stuck with this one for too many hours now, please help!
1st, do not name them with a # since you use that in the actual id. (you can add the # in when you need to seek them with jquery)
After that step the code you need is
$("#experiment a").hover(function(){
$( '#' + this.id.replace('_trigger', '_target') ).show();
}, function(){
$( '#' + this.id.replace('_trigger', '_target') ).hide();
});
This should be outside of the each loop since it automatically finds the relevant target.
You were also missing a sign = at the point that you assigned the id to the divs.
demo at http://jsfiddle.net/gaby/WJWe3/14/
Something like this maybe?
http://jsfiddle.net/WJWe3/11/
When you set the id for an element, it should not start with #. It's only when you use it as a selector in jQuery that it starts with #.
However, you don't even need to use the id. Create the a and div element as objects instead of as a string, then you can hook up the hover event directly to the link, and access the div directly, instead of trying to find it after adding it to the page.
jsfiddle.net/WJWe3/16/
var triggers = ["1_trigger", "2_trigger", "3_trigger"];
jQuery.each(triggers, function(i, val) {
var target = $('<div/>', { className: 'hidden' }).text('You found me!');
var link = $('<a/>', { href: '#' }).text(val).hover(function(){
target.stop().fadeTo("normal", 1.00);
}, function(){
target.stop().fadeTo("normal", 0.00);
});;
$("#experiment").append(link).append(target).append("<br/>");
});
here's how i would do this
http://jsfiddle.net/WJWe3/15/
<div id="experiment">
<p><a>test 1</a> <span class='hidden'>hidden 1</span></p>
<p><a>test 2</a> <span class='hidden'>hidden 2</span></p>
<p><a>test 3</a> <span class='hidden'>hidden 3</span></p>
</div>
...
$('#experiment a').hover(
function(){
$(this).siblings('span').stop().fadeTo("normal",1);
},
function(){
$(this).siblings('span').stop().fadeTo("normal",0);
}
);
Here's another that works.... Just for fun.
http://jsfiddle.net/WJWe3/18/

Categories

Resources