Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/Hide div based on matched json data

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?

like image 392
tour travel Avatar asked Mar 28 '26 23:03

tour travel


1 Answers

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();


    }
  });
}
like image 177
Farhan Tahir Avatar answered Mar 31 '26 04:03

Farhan Tahir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!