0

I am trying to get the value of data-scanID from the clicked tag and store it inside a variable called scanID but the alert comes up undefined.

$("#trucklist").click(function(event) {
    var scanID=$(event.target).data("scanID");
    alert(scanID);
});

The html looks something like this:

<ul id="trucklist">
    <li data-scanID=*somedata*>
        <ul>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
        </ul>
    </li>
    <li data-scanID=*somedata*>
        <ul>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
        </ul>
    </li>
    <li data-scanID=*somedata*>
        <ul>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
            <li>*stuff*</li>
        </ul>
    </li>
</ul>

1 Answer 1

5

You are targetting ul. Try this:

$("#trucklist > li").click(function(event) {
    var scanID=$(this).data("scanID");
    alert(scanID);
});

The above will target the trucklist's child li and alert you its data.

Also, I would suggest you to wrap the attribute's value within quotes.

Also, data attributes cannot contain capital letters. So change them or it will not work.

Demo

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer but that isn't working. I changed the data-scanID to just data-scan and used your code, now the click event isn't even firing. Also I can't put quotes around the data because all this html is being written from a for loop in an ajax call and the somedata is data brought in from the ajax. The data-scanID's do have the proper data in them though because I checked it with inspect element.
@chrispytoes in that case try $('#trucklist > li').on('click', function() { ... });.
@mdesdev Yeah still not working, the click event doesn't even get triggered.
@chrispytoes oook...try $(document).on('click','#trucklist > li', function() { ... });
Hi @chrispytoes if this or any answer has solved your question please consider accepting it by clicking the green check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this, though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.