Daniel Plas Rivera
Daniel Plas Rivera

Reputation: 400

hide by multi data attributes match existing variables with jquery/javascript

I'm trying to hide a div with two html data attributes for instance the one below which has html data attributes of Engineer and New York

 <div class="row" data-job-type="Engineer" data-job-location="New York"></div>
 <div class="row" data-job-type="Lockmsith" data-job-location="Maryland"></div>
 <div class="row" data-job-type="Wizard" data-job-location="New York"></div>

Below I tried to pass it in this way but it wouldn't work when I added the second attribute to it.

 var bar = "New York";
 var foo = "Engineer";

 $('.row[data-job-type=' + foo + ']','.row[data-job-location=' + bar + ']').hide();

Upvotes: 0

Views: 29

Answers (2)

Jobelle
Jobelle

Reputation: 2834

<html>
<head>
    <title>sample Page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

<script>
    $(document).ready(function () {

        $('.row[data-job-type="Engineer"][data-job-location="New York"]').hide();

    });    

</script>
</head>
<body>
<div class="row" data-job-type="Engineer" data-job-location="New York">1111</div>
 <div class="row" data-job-type="Lockmsith" data-job-location="Maryland">22222</div>
 <div class="row" data-job-type="Wizard" data-job-location="New York">333333</div>

</body>
</html>

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Since the attribute value has spaces in it, that has to be enclosed in " or '.

Also since you want to select elements with both the attributes, you need to combine them as below

var bar = "New York";
var foo = "Engineer";

$('.row[data-job-type="' + foo + '"][data-job-location="' + bar + '"]').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" data-job-type="Engineer" data-job-location="New York">1</div>
<div class="row" data-job-type="Lockmsith" data-job-location="Maryland">2</div>
<div class="row" data-job-type="Wizard" data-job-location="New York">3</div>

Upvotes: 1

Related Questions