I have a pretty straightforward (one would think) task.
Pass a value to a popup window and based on a click (proceed or cancel) perform an action using the value passed.
// on click we pass the value to the function testing - so far so good
$('#numbers').delegate('.icondelete', 'click', function(){
testing( $(this).attr('data-options') );
});
I pass the value found to a function, then try to assign it to a key
function testing(id){
//we can see that it passed successfully
alert("here it is: " + id);
//push the data into key data-id
$('#dodelete').data('data-id',id);
//but this alert doesn't return the value
alert("it should be here shouldn't it? " + $('#dodelete').attr('data-id'));
}
html
<div id='numbers' >
<div class='icondelete' data-options='123' >Set data-options as 123 - click here to test</div>
</div>
<br><br>
<div id='dodelete' data-id=''>landing div</div>
If you check out the fiddle http://jsfiddle.net/Microbe/cRLfC/4/ , you can see that the value is passed into the function no probs, but then when I try to assign it to the key it doesn’t.
Where am I going wrong?
When using
.data(), do not add thedata-prefix. When reading a value back, use.data("key"), not.attr(). I’d suggest reading this and looking at the code examples.So your code should look like this:
Settings values via
.data()does not actually set an attribute/property on the object with that value. The data is actually stored inside a jQuery data structure and it is retrieved not with.attr("key"), but with.data("key").If you want to set an actual attribute, do that with
.attr("key", value), though in jQuery coding, it’s generally better to use.data()than custom attributes.The only time you would use the
data-prefix yourself is if you put a custom attribute in your HTML like this per the HTML5 standard for custom attributes:Then, you could read that with this:
When querying the data value, jQuery will first look in its own internal storage. If not found there, it will look for an HTML5 data attribute that matches the name.