jquery DOM object custom variable atribute inside it - javascript

jQuery('<div/>', {
id: 'karta'+i,
znak: player1
}).appendTo('#igrac1');
znak:player1 one is the way that i tried to make custom atribute inside that object, but its wrong. So is it possible to have custom atribute inside jquery object ?

As others have said, when using jQuery, it's much safer to use .data() to store custom data on an element. You can do that compactly in your example like this:
jQuery('<div/>', {id: 'karta'+i,}).data("znak", player1).appendTo('#igrac1');
And, then when you want to reference the znak data, you get it with this:
var curPlayer = jQuery("#karta1").data("znak");
You can see it work here: http://jsfiddle.net/jfriend00/fqaKg/
If you want to set multiple data items on an object, you can do it either with multiple .data() calls or by passing an object to .data():
jQuery("#karta1").data("player", "Bob").data("age", 13);
or
jQuery("#karta1").data({player: "Bob", age: 13});
And, those can then be retrieved as:
var player = jQuery("#karta1").data("player");
var age = jQuery("#karta1").data("age");

Look at the jQuery.data() function, maybe you can use it in your case. Here is a fiddle with an example i've just made: http://jsfiddle.net/dRtqQ/
Here is the html:
<div id="igrac1"></div>
Here is the Js:
jQuery('<div/>', {
id: 'karta',
znak: 'hey'
}).appendTo('#igrac1');
var igracDiv= $("karta");
// store the information
jQuery.data(igracDiv, "test",{name:"Joe", age:12});
//then to read it (or put it in another variable)
alert(jQuery.data(igracDiv, "test").name);

If I'm understanding what you're trying to do, you need to use attr:
http://jsfiddle.net/HGz7D/
var newDiv = jQuery('<div/>', {
id: 'karta'
}).attr(znak,player1)
or you could do this:
var details = {
id: 'karta'
};
details[znak] = player1;
var newDiv = jQuery('<div/>', details).appendTo('body');
But as stated in the other question, data is usually a better idea than custom attributes.

You're setting an attribute znak to the value of player1. In other words the element would look like this
<div id="kart1" znak="<!-- value of player` -->"></div>
You might be looking for $.data to store a value for the element.

Related

Accessing a Dynamically Named array in jQuery/javascript

I wish to name an array according to the table row containing the button that was clicked.
I get the table row thus:
var rowNum = $(this).parent().parent().index();
Now, I wish to name the array and access it.
var arrayName = 'arrTR' + rowNum;
window[arrayName] = new Array();
window[arrayName]["First"] = "Bob";
window[arrayName]["Last"] = "Roberts";
window[arrayName]["email"] = "me#there.com";
//The array should be accessible as arrTR__
alert(arrTR1["Last"]);
The alert does not work, so I am doing something wrong.
How should I refactor the code to allow me to update and access the array?
jsFiddle
What you're doing with the dynamically named variables is essentially creating an array of those variables (one for each rowNum), but giving each of those array elements its own individual named variable.
There is a much better way to do this. Instead of generating a series of dynamically named variables, make a single array or an object. Then add an element or property for each of the dynamically named variables you were going to generate.
Your test code could look like this:
var arrTR = [];
var rowNum = 1;
arrTR[rowNum] = {
First: 'Bob',
Last: 'Roberts',
email: 'me#there.com'
};
alert( arrTR[1].Last );
Alternatively, you can do something with $.data as mentioned in Johan's answer. But if you do use plain JavaScript code, use a single array as described here instead of multiple dynamically named variables.
There are several reasons to do it this way. It's cleaner and easier to understand the code, it may be faster when there are large numbers of entries, and you don't have to pollute the global namespace at all. You can define the var arrTR = []; in any scope that's visible to the other code that uses it.
Arrays and objects are made for keeping track of lists of things, so use them.
There is nothing wrong with your code, and the only place it has error is the alert since it is not defined on the first click button
see this fiddle with a little update
if(rowNum === 1)
alert(arrTR1["Last"]);
else if(rowNum === 2)
alert(arrTR2["Last"]);
fiddle
How about something like this?
$('.getinfo').click(function() {
var result = $('table tr:gt(0)').map(function(k, v){
return {
firstName: $(v).find('.fname').val(),
lastName: $(v).find('.lname').val(),
email: $(v).find('.email').val(),
}
}).get();
//update to show how you use the jQuery cache:
//1. set the value (using the body tag in this example):
$('body').data({ result: result });
//2. fetch it somewhere else:
var res = $('body').data('result');
});
Not sure how you want to handle the first row. I skip in in this case. You can access each row by result[index].
As you might have noticed, this saves all rows for each click. If you want to use the clicked row only, use the this pointer.
http://jsfiddle.net/nwW4h/4/

jQuery - Choosing a variable based on the ID of the element that was clicked

I'm probably overlooking a more obvious way to do what I want, but...
I have a list of JS variables with names that are identical to the ID's of some elements on my page. When I click one of the elmeents, I want to be able to use the clicked element's ID to determine which variable should be used in my function. My variable names correspond to my element ID's - there must be some way to take the value of my clicked element's ID using $(this).id and then find the variable that matches that string? Just to be clear, the content of the variables is not at all related to the variable names or element ID's - the variables are set when the page loads and I'd like to avoid setting them every time the function is run! And I know I could probably use onclick for this, but I'm trying to avoid that because apparently it's inferior now?!
Thanks!
I recommend you to make an array with al of your ids names
thisArray = {
uniqueID1: 'Your value for uniqueID1',
uniqueID2: 'Your value for uniqueID2'
};
you can call an element by a class for example
HTML:
<div id="uniqueID1" class="elements_class"> Div Content </div>
<div id="uniqueID2" class="elements_class"> Div Content </div>
jQuery:
$('div.elements_class').click(function(){
var now_id = $(this).attr('id');
alert(thisArray[now_id]);
});
It seems like what you want is to use .data():
$(el).data('myobject', {
x: 123,
y: 456
});
Then to retrieve:
$(el).on('click', function() {
var obj = $(this).data('myobject');
});
Did you think of storing them in an object?
Example :
var obj = {
'id1' : value1,
'id2' : value 2,
//...
}
Then you can acces them like that
obj[this.id]
If you use an object to store the variables you are talking about with key/value pairings, you can just call variableObject[this.id] to get that variable.

JQuery - get attr/text from HTML string in a variable

I have a HTML string that I'm passing through a function and I want to be able to perform Jquery methods on that variable from inside the function - such as .attr('href') or .text(). I'm sure there is a simple solution for this and something more elegant then temporarily appending the DOM.
HTML
<div class="here"></div>
Javascript
link = 'Google';
// This works
$('.here').html(link);
works = $('.here').text();
console.log(works);
// This doesn't
not = link.text();
console.log(not);
http://jsfiddle.net/dfgYK/
You need to create a jQuery object from link in order to use jQuery methods on it. Try:
not = $(link).text();
DEMO: http://jsfiddle.net/dfgYK/1/
Depending on what you're doing with link, it might be beneficial to do this earlier in your code so that you can just use something like:
var $link = $(link);
console.log(link.text());
You can make a jQuery object that is not part of the DOM by passing a string in:
link = $('Google');
Then, jQuery methods will work on it:
var text = link.text();
Create the link with jQuery instead:
var link = $('<a />', {
href: "http://www.google.com",
text: "Google"
});
Then you can access it's properties with link.text() like you wanted.

Adding custom data attribute for a new node in Jquery does not work

I tried to use the method data (jQuery 1.7.1) in this code:
var q = '<div class="form-error-marker"></div>';
var t = $(q).data('message', message).insertAfter(el);
and it does not work.
Note that this works:
var t = $(q).attr('data-message', message).insertAfter(el);
Why does the first variant not work?
EDIT: insertAfter works correctly and new div is added after el (which is instance of one element which I get by getElementById() function; long story short I have a library that I extend).
When I say 'it does not work' I mean that the attribute 'data-message' is not stored.
Using data like that sets an arbitrary piece of data for this node; it doesn't add a new data- attribute. Just add the attribute with the attr function, and then access it with data
var q = $('<div class="form-error-marker"></div>').attr("data-message", message);
Now access it like this:
var message = q.data("message");
Here's a fiddle
When you use jQuery.data you don't change element attributes, instead your data saved in $.cache.
So if you want to change element attributes use jQuery.attr, when you want to save some info use jQuery.data

JavaScript/JQuery: use $(this) in a variable-name

I'm writing a jquery-plugin, that changes a css-value of certain elements on certain user-actions.
On other actions the css-value should be reseted to their initial value.
As I found no way to get the initial css-values back, I just created an array that stores all initial values in the beginning.
I did this with:
var initialCSSValue = new Array()
quite in the beginning of my plugin and later, in some kind of setup-loop where all my elements get accessed I used
initialCSSValue[$(this)] = parseInt($(this).css('<CSS-attribute>'));
This works very fine in Firefox.
However, I just found out, that IE (even v8) has problems with accessing the certain value again using
initialCSSValue[$(this)]
somewhere else in the code. I think this is due to the fact, that I use an object ($(this)) as a variable-name.
Is there a way arround this problem?
Thank you
Use $(this).data()
At first I was going to suggest using a combination of the ID and the attribute name, but every object might not have an ID. Instead, use the jQuery Data functions to attach the information directly to the element for easy, unique, access.
Do something like this (Where <CSS-attribute> is replaced with the css attribute name):
$(this).data('initial-<CSS-attribute>', parseInt( $(this).css('<CSS-attribute>') ) );
Then you can access it again like this:
$(this).data('initial-<CSS-attribute>');
Alternate way using data:
In your plugin, you could make a little helper function like this, if you wanted to avoid too much data usage:
var saveCSS = function (el, css_attribute ) {
var data = $(el).data('initial-css');
if(!data) data = {};
data[css_attribute] = $(el).css(css_attribute);
$(el).data('initial-css', data);
}
var readCSS = function (el, css_attribute) {
var data = $(el).data('initial-css');
if(data && data[css_attribute])
return data[css_attribute];
else
return "";
}
Indexing an array with a jQuery object seems fishy. I'd use the ID of the object to key the array.
initialCSSValue[$(this).attr("id")] = parseInt...
Oh please, don't do that... :)
Write some CSS and use the addClass and removeClass - it leaves the styles untouched afterwards.
if anybody wants to see the plugin in action, see it here:
http://www.sj-wien.at/leopoldstadt/zeug/marcel/slidlabel/jsproblem.html

Categories