ak85
ak85

Reputation: 4264

jQuery target this data-attribute

I have the below code working as expected. as shown in this fiddle.

    <div id="test-a" class="test">
        <ul>
            <li data-typea="1">Option 1a</li>
            <li data-typea="2">Option 2a</li>
            <li data-typea="3">Option 3a</li>
        </ul>
    </div>

    <div id="test-b" class="test">
        <ul>
            <li data-typeb="1">Option 1b</li>
            <li data-typeb="2">Option 2b</li>
            <li data-typeb="3">Option 3b</li>
        </ul>
    </div>

    <input name="typea" id="typea" type="number" value="0">
    <input name="typeb" id="typeb" type="number" value="0">

    <script>
        $(document).on('click', '#test-a li', function (event) {
            var view_typea = $(this).attr('data-typea');
            $('#typea').val(view_typea);
        });

        $(document).on('click', '#test-b li', function (event) {
            var view_typeb = $(this).attr('data-typeb');
            $('#typeb').val(view_typeb);
        });
    </script>

The problem I have is I want to have several test classes on the page and don't want to write an individual click event for each one.

so I want something like this.

    <script>
        $(document).on('click', '.test li', function (event) {
            var id =$(this).closest('.test').attr('id') || '';
            id = id.replace(/test-/,'');
            var view_type = $(this).attr("[data*='type']");
            console.log(id);
            console.log(view_type);
            $('#type' + id).val(view_type);
        });
    </script>

But the view_type attribute is coming through as undefined, where am I going wrong here?

Upvotes: 0

Views: 520

Answers (3)

adeneo
adeneo

Reputation: 318222

You can't use the attribute contains selector to get data attributes, but you could just use the ID like the other answers.

If the ID for some reason doesn't match the data attribute, you could create your own method that accepts regex

$.fn.regData = function(reg) {
    for (key in this.data()) {
        if (key.match(reg)) return this.data(key);
    }
}

and just use it like

var view_type = $(this).regData(/^type/); // string starts with "type"

FIDDLE

that way you could match almost anything.

Upvotes: 1

RGS
RGS

Reputation: 5211

   <script>
        $(document).on('click', '.test li', function (event) {
            var id =$(this).closest('.test').attr('id') || '';
            id = id.replace(/test-/,'');
            var view_type = $(this).data("type" + id);
            console.log(id);
            console.log(view_type);
            $('#type' + id).val(view_type);
        });
    </script>

You have missed 'id' in your data attribute selection of view_type.

Demo:

http://jsfiddle.net/5Zdkv/

Upvotes: 2

Mukesh
Mukesh

Reputation: 858

modify view_type variable to below code, you can access data-attr directly using data .

var view_type = $(this).data("type" + id);

Upvotes: 1

Related Questions