I want add style where data attribute value is same as ajax get request
My jquery code:
jQuery(function($) {
get_stock();
function get_stock(){
$.ajax({
url: vdisain_vd.url,
type: 'GET',
success: function(res) {
console.log(JSON.parse(res)); // [ { "unique_id": "Warehouse A available", "available": "1" }, { "unique_id": "Warehouse B available", "available": "0" } ]
$.each(JSON.parse(res), function (i, item) {
console.log($(this).data('shape-title'))
if($(this).data('shape-title') == item.unique_id) {
$(this).attr('style', 'color:blue');
}
console.log('item: ' item.unique_id)
});
setTimeout(function() { get_stock(); }, 1000)
}
});
}
});
Example if warehouse is not available I want add color:blue;
and if available then color:green;
data-shape-title == unique_id
CodePudding user response:
You need to use an attribute selector to find the element whose data-shape-title
attribute is the same as unique_id
.
let res = [ { "unique_id": "Warehouse A available", "available": "1" }, { "unique_id": "Warehouse B available", "available": "0" } ];
$.each(res, function(i, item) {
el = $(`[data-shape-title="${item.unique_id}"]`);
if (item.available == "1") {
el.css('color', 'blue');
} else {
el.css('color', 'green');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-shape-title="Warehouse A available">
Warehouse A
</div>
<div data-shape-title="Warehouse B available">
Warehouse B
</div>