I am trying to compare the values of two elements, and if they share that value, execute a .css() modifier upon one of them. The issue is that some of my comparing elements have values in a comma separated list: normal values: "400", "500" comma'd values "600, 602" "502, 504"
My jQuery is as follows:
jQuery('#container1 > div[booth-number="{Booth Assignments}"]').css('background-color','white')
as you can see I'm using a merge tag to indicate the booths that i'd like to have their background color modified with.
I was also trying something like a forEach loop:
const booths = [{Booth Assignments}]
booths.forEach(jQuery('container1 > div[booth-number=jQuery(this)]').css('background-color', 'white')
which does not seem to work either. could really use some help here!
CodePudding user response:
First, you can take the array and join it with a comma, replace the spaces, then split it on the comma. This will allow you to loop through the items.
Next, I'm using a data attribute since booth-number isn't valid.
Since you are using jquery, I'm also just using $.each
let booths = ["600, 602", "502, 504"].join(",").replace(/[\s]/g, "").split(",");
$.each(booths,function(index,booth) {
$('#container1 > div[data-booth-number="' booth '"]').css('background-color', 'red')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container1">
<div data-booth-number="600">608</div>
</div>
CodePudding user response:
Your foreach syntax is incorrect.
const booths = ["this", "is", "dummy", "data", "and,some,more", "dummier,datas"].join(",").replace(/[\s]/g, "").split(",");
console.log("All booths: ");
console.log(booths);
console.log(" "); // Blank line for readability
booths.forEach(function(booth_number) {
$('container1 > div[booth-number=' booth_number ']').css('background-color', 'white');
console.log("This should color booth \"" booth_number "\" white.");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>