PositiveGuy
PositiveGuy

Reputation: 47743

Trouble setting data with $.data()

I can't seem to get this to store. I now that the id and name are definitely valid as I alerted them out right before this code was called:

$('#carText').data("carId", carId);
$('#carText').data("carName", carName);

alert("value stored for carId: " + $("#carText").data("carId").carId);

I get undefined when I try to alert out the value that I supposedly stored.

Upvotes: 3

Views: 284

Answers (6)

SirCommy
SirCommy

Reputation: 260

data() is based on key:value data, and since all you're storing is a simple value (a string) you don't need to specify .carId at the end. The "route" $(select).data("keyName") is sufficient.

Upvotes: 0

Ilia Sachev
Ilia Sachev

Reputation: 76

You don't need to use .carId at the end. It's right.

But some problems with data attribute may causes when you try to get properties which named in camelcase style

Try to rename you data properties to 'carid','carname' It should work

You code may looks like

HTML

<div id="carText" data-cardid="VAZ_1118" data-carname="Lada_Kalina">

Javascript

alert("value stored for carId: " + $("#carText").data("carid"));

Upvotes: 0

Andrew Jackman
Andrew Jackman

Reputation: 13966

Your alert should look like this: alert("value stored for carId: " + $("#carText").data("carId"));

Upvotes: 0

Kris Ivanov
Kris Ivanov

Reputation: 10598

don't need the .cardId at the end

alert("value stored for carId: " + $("#carText").data("carId"));

Upvotes: 2

Richard Dalton
Richard Dalton

Reputation: 35793

You've stored the data as carId, you don't need that .carId after retrieving it:

alert("value stored for carId: " + $("#carText").data("carId"));

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

You appear to be using incorrect syntax to retrieve the stored data. Try the following:

alert("value stored for carId: " + $("#carText").data("carId"));

Upvotes: 0

Related Questions