Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

For some reason, the jquery .data() method is only working when the data is set using jquery. Attempting to retrieve data attributes set in the html results in a return value of null or undefined. Here is my javascript and html.

var ico = "<span class='deleteTag'></span>";
var x = "<span class='usertag' data-id='" + ui.item.userid + "'>" + ui.item.label+ " " + ico + "</span>";
$("#" + id + " .userEditor").prepend(x);

$("#" + id + " .userEditor .deleteTag").bind("click",function(){
    alert($(this).parent().attr("data-id"))
    alert($(this).parent().data("id"));
    alert($("#testdivv").data("hola"));
    $(this).parent().data("yolo","swag");
    alert($(this).parent().data("yolo"));                                     
    // $(this).parent().remove();
});
<form method="post">
    <div id="#testdivv" data-hola="hello"></div>
    <div id="user1"><div class="userEditor" style="border:1px solid gray;">
        <input style="border:0px;width:600px;" type="text" onKeyUp="if(event.keyCode != 13 && event.keyCode != 40)userSuggest('user1');"/>
    </div>
    <div class="userSuggestions"></div>
    <input name="IDList"  class="hiddenPut" type="hidden" /></div>
</form>
share|improve this question
1  
Use $(element).attr('data-id'); to get a html attribute. –  I didn't understand... 14 mins ago
    
jQuery's data is more than just reading attributes: api.jquery.com/data –  Alex 13 mins ago
    
Put the JS code inside ready handler: `$(document).ready(function() { your code here }); –  hjpotter92 13 mins ago
    
This may also help: stackoverflow.com/q/23592030/3132718 –  I didn't understand... 12 mins ago
    
What version of jQuery are you using? –  Musa 11 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.