8

i have the following problem using jquery.

I have sth like this

<div id="yxz" value="1">
  <span class="delete"></span>
</div>

now I have this fn but it only returns "undefined", it does however return the id, or class if I ask for this.

$(".delete").click(function(){
  alert($(this).parent("div").attr("value"));
});

I used to get this value with the same attr stuff. Does this have sth to do with me using the jquery 1.6.1 now instead of 1.5.2.

Thanks for your help.

Lukas Oppermann
  • 2,918
  • 6
  • 47
  • 62

5 Answers5

5

I can confirm this code snippet works perfectly in Chrome 11, Firefox 4 and IE 9 using the jQuery Git version.

EDIT: For the ones advising prop(), check the docs. Prop() is used for boolean attributes like: checked, disabled etc.

Melvin
  • 547
  • 2
  • 10
3

To retrieve the value of elements, use val(). Since divs don't have values, you should use data() to set and get data.

Tim Büthe
  • 62,884
  • 17
  • 92
  • 129
  • Well, I did not really use data() since my values come from the db and are already there, but using data="1" instead of value="1" and than .attr("data") did work. With jquery 1.5 the value thing worked as well. – Lukas Oppermann Jun 10 '11 at 11:32
  • 2
    @Lukas: I think he meant for you to use `data-value="1"` and then `.data('value')` – Markus Hedlund Jun 10 '11 at 12:18
  • 1
    actually, the data function doesn't set any attributes to the element. It's just an internal map, that stores data to a given element. However, "value" is an kind of an reserved thing and should be avoided in such situations. Glad you got it done. – Tim Büthe Jun 10 '11 at 12:23
  • I just figured this out myself too, but thanks anyway. I am using it like you suggested now. :) – Lukas Oppermann Jun 10 '11 at 13:57
0

if using the latest jQuery, try with:

$.prop(propertyName);

Gary Green
  • 22,045
  • 6
  • 49
  • 75
metaforce
  • 1,337
  • 5
  • 17
  • 26
0

Yes, since jQuery 1.6 I think you need to use .prop() instead of attr().

Markus Hedlund
  • 23,374
  • 22
  • 80
  • 109
0

Your code appears to work fine in this fiddle, using jQuery 1.6

James Allardice
  • 164,175
  • 21
  • 332
  • 312