I have a function to load all data from JSON file and I show matched data if data[i]['brand_id'] == modelId
<script>
function loadModel(modelId) {
$.ajax({
type: "POST",
dataType: 'json',
url: '/api/model.json',
success: function (data) {
$.each(data, function (i, v) {
if (data[i]['brand_id'] == modelId) {
$('#item-brand-list').append('<option data-brand-id="' + modelId + '" value="' + data[i]['id'] + '">' + data[i]['name'] + '</li>');
}
});
}
});
}
</script>
This function will be execute on this snippet:
<script>
$(document).on('click', '.SelectOption', function () {
var val = $(this).attr('data-val');
loadModel(val); // here
});
</script>
For example if any data (from JSON) equal by given modelId
it append matched data into select option
but I want to hide select-ads-brand
if there is no match.
I tried:
<script>
if (data[i]['brand_id'] == modelId) {
$('#select-ads-brand').show();
$('#item-brand-list').append('<option data-brand-id="' + modelId + '" value="' + data[i]['id'] + '">' + data[i]['name'] + '</li>');
} else {
$('#select-ads-brand').hide();
}
</script>
HTML:
<div id="select-ads-brand">
<select id="item-brand-list">
<option>-- Select --</option>
</select>
</div>
But no success, I think it's bad logic to show hide that div
.
Any suggestion?
Try using the following:
function loadModel(modelId) {
$.ajax({
type: "POST",
dataType: 'json',
url: '/api/model.json',
success: function(data) {
var foundMatch = false;
$.each(data, function(i, v) {
if (data[i]['brand_id'] == modelId) {
$("#select-ads-brand").show(); // if match found show the div
$('#item-brand-list').append('<option data-brand-id="' + modelId + '" value="' + data[i]['id'] + '">' + data[i]['name'] + '</li>');
foundMatch = true; // set variable to true on success of match
}
});
// if no match found simply hide the div
if(!foundMatch) $("#select-ads-brand").hide();
}
});
}
you can just make use of filter
function and do check like this
const filtereddata = data.filter(ele => ele['brand_id']==modelId);
if(filtereddata.length > 0)
{
//add filtered data
$.each(filtereddata, function (i, v) {
$('#item-brand-list').append('<option data-brand-id="' +
modelId + '" value="' + data[i]['id'] + '">' + data[i]
['name'] + '</li>');
});
//show
$('#select-ads-brand').show();
}
else
{
//hide
$('#select-ads-brand').hide();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.