Im having a problem setting options to an array value in a jQuery plugin using data attributes.
If I reference the data attribute using a class selector
$('.tm-input').tagsManager(
{
prefilled: $('.tm-input').data('load')
})
It works but all the elements get the same values.
If I reference using "this" it sets the correct values but it comes across as a string not an array.
$('.tm-input').tagsManager(
{
prefilled: $(this).data('load')
})
I've tried using JSON.parse() but I get an error about an unexpected character. Any help would be appreciated!
Have you tried each
$('.tm-input').each (function () {
$(this).tagsManager( { prefilled: $(this).data('load') });
});
Explanation:
When a selector has more than 1 element, applying a method to it will typically affect all of the elements, but retrieving a property will typically only return that property from the 1st element.
So when you use .tagsManager on your $('.tm-input') selector, you are applying .tagsManger to all of the elements. But when you set prefilled:$('.tm-input').data('load'), the data method is only grabbing the data from the first element in the list, every single time.
When you use each, it applies the logic inside of the each block to each element individually, rather than all of them at once, so when you use $(this).data('load'), it grabs the load attribute from each individual element as well.
Related
When I click on a "trash" button I want to delete the message block. There are multiple message blocks but they all have unique data-values. The id of the targeted block I want to delete is stored in the data-value of .send-message-button.
I tried making a variable that I could pass onto the targeted .messageblock element. I checked with an alert to see if the variable gets the proper number, which it does. However when I alert the whole thing, it gives [object object] (without the .remove, of course).
How can I do this?
var trashid = $(".send-message-button").attr("data-value");
$('.message-block').attr("data-value", trashid).remove();
If you want to retrieve an element using the value of one of its attributes you need to use the attribute selector, not the setter of the attr() method.
There's two main ways to do this. Firstly if the data attribute is present in the DOM then you can use an attribute selector:
var trashid = $(".send-message-button").data('value');
$('.message-block[data-value="' + trashid + '"]').remove();
Alternatively if the data attribute is held in jQuery's cache (as will be the case if you use data() as a getter/setter, as you should be) then you can use filter() instead:
var trashid = $(".send-message-button").data('value');
$('.message-block').filter((i, e) => $(e).data('value') === trashid).remove();
I have some div elements with the same class. I want to iterate through them. I am using jquery ".each" in order to do it. I also want to access each element individually and toogle its class so I need to get the index of the element within the class elements array. I currently have a code similar to this:
$('.the_div_class').each(function(i, obj) {
if("a certain condition") {
$('.the_div_class')[0].toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class;
}
}
However I receive an error saying "$(...)[0].toggleClass is not a function". If I don't specify an index I toogle all the elements of the array... I console.log the "$('.the_div_class')" array and get a structure similar to this:
[div.the_div_class, div.the_div_class, div.the_div_class, div.the_div_class, div.the_div_class, prevObject: r.fn.init[1]]
And if I console.log "$('.the_div_class')[0]" I get this:
<div class="the_div_class">
Why doesn't it work and what should I do in order to make it work?
The code $('.the_div_class')[0] will only get the first element that matches that selector in the DOM with that class naively, it doesn't work because it's no longer a jQuery object (hence it doesn't have the method .toggleClass()). Inside .each() you can use this to refer to the current element being iterated:
$('.the_div_class').each(function(i, obj) {
if("a certain condition") {
$(this).toggleClass('other_div_class');
}
}
Note: To get a item by it's index in jQuery you can use .get(). For example:
$('.the_div_class').get(0).toggleClass('other_div_class');
Change your code to:
var collection = $('.the_div_class');
collection.each(function(i, obj) {
if("a certain condition") {
$(collection[0]).toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class;
}
}
You need to recreate jQuery object by passing DOM element to $ again, i.e $($('.the_div_class')[0]) for your code.
When you specify the index, you're fetching the plain javascript element that was selected with jQuery, not a jQuery object. This is why the toggleClass() method is unavailable to you.
You can wrap it in jQuery like this $($(selector)[i]) to convert it back to a jQuery object. However, the arguments supplied with the each loop are your friend here. That is, you can access the current object in the loop with $(obj).
You need to change the code to get element by using this keyword:
$('.the_div_class').each(function(i, obj) {
if("a certain condition") {
$(this).toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class;
}
}
I have this problem in my JavaScript class:
//===== i set this data record
jQuery(element).data("types", "row");
console.log(jQuery(element).data("types")); // writes "row" (the element is a div)
//==== into other method
//==== i want find all element with data-types = row
console.log(jQuery("[data-types='row']").length); // writes 0
jQuery("div").each(function(i,e){
console.log(i, jQuery(e).data(), jQuery(e).attr("id")); // writes object{type:row}
});
why with this jQuery("[data-types='row']") i can't find elements ???
When you assign data to an element using jQuery.data() it does not update the data-* attribute of the element; you therefore cannot use attribute selectors to select the element.
The data- attributes are pulled in the first time the data property is
accessed and then are no longer accessed or mutated (all data values
are then stored internally in jQuery).
In order to select these elements you can use the filter() function with custom function:
jQuery("div").filter(function() {
return $(this).data("types") === "row";
});
Note: If you are also using jQuery UI you would find the :data(key) selector useful.
The data() method only uses the DOM when initially reading from an element. When you use it to add or change the data of an element, it puts the data in its internal memory, it doesn't modify the DOM. So DOM selectors won't find it. From the documentation:
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
To find all the elements, you can use .filter():
jQuery("div").filter(function() {
return $(this).data("types") == "row";
});
$(function(){
var z = document.body.children[0];
var x=$("li", z);
x.name="Johnny";
alert(x.prop(name));
});
x should be an object containing all the elements within the first ul in the body.
Regardless of what the object contains, I would like to add a property with a value, and then use the prop() method to show it - but that doesn't seem to work. Why is that?
I saw a script containing the following: var $x = $("div"); - Do I have to add $ to the variable name if it's a jQuery object?
To select the first ul element inside a page you can do:
$("ul:first li")
This way you are going to select all lines inside the first list in the page.
To store arbitrary data in an element you can use the method data, like this:
$("element").data('key', 'value');
and to retrieve the data:
$("element").data('key');
More info, for the data method.
If you really want to add an attribute you can use the attr method, it works the same way as the data method, but it would reflect in the DOM.
If you want all li elements in the first ul element, then this should do the trick:
var elements = $("ul:eq(0) li");
Here is a very simple example of this in action.
In regards to setting a property, you can do element.name = "test" and it will work ok. But what you need to understand is that this is setting a name property on the jquery collection object and NOT on any of the actual elements.
What you can do however, is set the property like so:
elements.prop("name", "test");
and the access it like so:
var name = elements.prop("name");//name will be "test"
Here is a working example
As I mentioned in my comment, you don't need to prefix the variable with $. But this can be helpful to easily see which variables are JQuery objects.
Number 1. x is a jQuery object, you added to that instance a name property, then you're using name though it wasn't defined.
If you want to change a property of the element you got with jQuery the ways are:
$('selector').prop('property', 'value');
$('selector').attr('attribute', 'value');
$('selector').get(index).property = "value";
Number 2. no you don't have to, $ prefix is simply a convention to make the code more readable.
Is there any specific reason behind using $ with variable in jQuery
Using the selector from #musefan answer, you can take the collection returned, and use the attr() method to add an attribute and value to each item selected. However, I've modified his selector slightly to actually grab "all" elements in there, (just in case future visitors wonder)
var elements = $("ul:eq(0)").children();
elements.attr("attrName", value);
So if you wanted to set the title:
var elements = $("ul:eq(0)").children();
elements.attr("title", "Johnny");
You probably don't want to alert these values, browsers may ask you to stop allowing alerts on the page... but if you really did, then you could throw in an .each() after that.
var elements = $("ul:eq(0)").children();
elements.attr("title", "Johnny").each(function(){
alert($(this).attr("title");
});
I just started using jQuery, and various sources suggest that the following should be used to reference an element by ID:
$("#imgThumbnail")
theoretically making something like this possible:
$("#imgThumbnail").src;
But my testing indicates that something like $("#imgThumbnail") returns an array, making the following necessary:
$("#imgThumbnail")[0].src;
Do I really need to reference by the index of the array every time I am trying to reference something by ID (i.e., var oObj = $("#someobjectid")[0]; )?
You should get the src attribute to get the value
$("#imgThumbnail").attr('src');
This post explains what the $ function returns and various ways to use it.
$(selector)
Returns a jQuery object, which could contain a number of DOM elements.
$(selector)[0] or $(selector).get(0)
Returns the first result as an actual DOM element.
$(selector).eq(0) or $($(selector).get(0))
Returns the DOM element wrapped in a jQuery object so that we can do stuff like:
$(selector).eq(0).addClass("deleted").fadeOut();
$(specifier) will return a collection, so yes if you want to call something on an individual member you need to pick which one. In most cases though there is a collection operator you can use to achieve the same result. For instance, you could call $('#imgThumbnail').attr('src', 'value')
You should bear in mind that it's not really an array, it's a jQuery object which, among other things, allows array-style access
$(whatever)
returns the jQuery object. On the jQuery object you can do jQuery and jQuery plugin things, eg. .text() to return the text inside the element or .css("background", "pink") to make the element(s) pink.
Since src isn't a jQuery thing you cannot access it. src is however both a HTML attribute, and you can access those with the attr method:
.attr("src")` and `.attr("src", "http://www.example.com/myimage.png")
src is also a DOM-property and you can access DOM-properties using [index] or by iterating through the jQuery object with each:
.each(function(){
this.src = "http://www.example.com/myimage.png";
})
I don't think you should be using .src with jQuery.
Try $("#imgThumbnail").attr('src');
(this will read the src attribute, you set it with a second arg if you like)
See here:
http://docs.jquery.com/Attributes/attr
to set the src attribute use
$("#imgThumbnail").attr("src", value)
if you use something like a class selector or tag like so
$("img").attr("src", value)
It will modify all the image src attributes on the page. Hence the $ function returns an array.
And you do not need to reference it specifically.