SilentCry
SilentCry

Reputation: 2092

jQuery - set .html() to element by it's data-for attribute

please, is there any way to put content into element with not know id or class, but by it's attribute? I have somewhere on the page more of this twins:

<input id="someSpecialId" class="autocomplete"/>
<ul data-for="someSpecialId"></ul>

List can be anywhere on page, not next to input. In jQuery I have this:

$(document).on('keyup', '.autocomplete', function() {
    var sectionName = 'autocomplete';
    var min_length = 2; 
    var inputID = $(this).attr('id');
    var keyword = $(this).val();
    var $output = // HERE I NEED TO PUT FOUND ELEMENT BY IT'S data-for = inputID
    if (keyword.length >= min_length) {
        $.ajax({
            url: 'php/readDB.php',
            type: 'POST',
            data: {section: sectionName, keyword:keyword},
            success:function(data){
                $output.show();
                $output.html(data);
            }
        });
    } else {
        $output.hide();
    }
});

Do you have any ideas, please? Thank you very much for answer.

Upvotes: 0

Views: 143

Answers (2)

nethopp3r
nethopp3r

Reputation: 111

You can use selector attributes for this. In general they look like this: [attribute="value"] In your case, you would use something like this:

$('ul[data-for="'+inputID+'"]');

These work both in CSS and jQuery. Here's a code snippet with an example for both:

$('[data-for="second_input"]').html("<li>Item</li>");
[data-for="second_input"] {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input type="text" id="first_input" />
  <ul data-for="first_input"></ul>
  <input type="text" id="second_input" />
</div>
<ul data-for="second_input"></ul>

Upvotes: 2

Scimonster
Scimonster

Reputation: 33409

var $output = $('[data-for="'+inputID+'"]');

The attribute equals selector.

Upvotes: 4

Related Questions