Show specific elements in a listview using JavaScript

I have created a dynamic listview using jQuery Mobile that currently shows 4 list items. The list is generated through JavaScript.

$( document ).ready(function() {
var data = [{
        "name": "Light Control",
        "category": "category",
        "info": "Click for light control",
        "img": "light_control"
}, {
        "name": "Power Outlet",
        "category": "category",
        "info": "Click for power outlets",
        "img": "power_outlets"
}, {
        "name": "Single Switch",
        "info": "One button, one lamp",
        "img": "blind_control"       
}, {
        "name": "Double Switch",
        "info": "Two buttons, two lamps",
        "img": "multimedia"     
}];

var output = '';
$.each(data, function (index, value) {
    if(value.category === 'category') {
        output += '<li><a href="#">'
        output += '<img src="img/' + value.img + '.jpg">'
        output += '<h2>' + value.name +'</h2>'
        output += '<p>' + value.info + '</p>'
        output += '</a></li>';
    }
});

$('#list_zoek_category').html(output).listview("refresh");

});

Currently, the list displays each row from the data as a list item. However, I want to only display the list items where category equals "category".

Does anyone have any suggestions on how I can achieve this?

Answer №1

Here is an example of how to proceed:

$.each(data, function (index, value) {
    if(value.category === 'category')
    {
        output += '<li><a href="#">'
        output += '<img src="img/' + value.img + '.jpg">'
        output += '<h2>' + value.name +'</h2>'
        output += '<p>' + value.info + '</p>'
        output += '</a></li>';
    }
});

Answer №2

$.each(data, function (index, value) {
    if(value.category == "category") {
        output += '<li><a href="#">'
        output += '<img src="images/' + value.picture + '.jpg">'
        output += '<h3>' + value.title +'</h3>'
        output += '<p>' + value.description + '</p>'
        output += '</a></li>';
    }
});

untested code but worth a shot.

Answer №3

To implement a conditional test, start by verifying if the object contains a category property and then confirm if it meets your criteria:

let result = '';
$.each(data, function (index, value) {

    if (value.category && value.category === 'category') {
        result += '<li><a href="#">';
        result += '<img src="img/' + value.img + '.jpg">';
        result += '<h2>' + value.name +'</h2>';
        result += '<p>' + value.info + '</p>';
        result += '</a></li>';
    }

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulate the value of the <input> element when focused through JavaScript

After I focus on the input field, I was expecting to see Bond-Patterson, but instead, I am only getting Bond. What could be causing this discrepancy and how can it be fixed? $('input[name="surname"]').attr("onfocus", "this.placeholder='Bo ...

"Exploring the use of conditional rendering in React to dynamically hide and show components based

I am currently immersed in the world of React/Redux, focusing on an e-commerce project. This particular application offers two payment methods: cash and card payments. On the product display page, both payment icons are visible. However, I am seeking a sol ...

Creating a navigation bar that stays fixed at the top of

Hey there, currently I am utilizing a combination of jquery and css to affix my navigation menu at the top when scrolled. However, the problem is that my navigation menu is positioned beneath a div with a height set in viewport units (vh). The jquery scr ...

How to create a sequence of queries to a mongoDB database (using mongoose) depending on a condition

Source Code let placeForSearch="hampi" let filteredHotelFacilities=req.body.filter //["Free Wifi"] let hotels = await Hotel.find({placeForSearch}) .where("facilities") .select(selectedProperties) .skip(pageNu ...

I did not anticipate the React setState function to behave in the manner it did

While working on form validation for my page, I came across a tutorial showcasing a validation method that seems to be functioning correctly. However, there is one aspect that I am struggling to grasp. The tutorial suggests declaring a variable before the ...

Comparing v-show(true/false) and replaceWith: Exploring the best practice between Vue and jQuery

Currently, I am in the process of learning vue.js and have a question regarding the best approach to implement the following scenario: The main query is whether it is acceptable in HTML to write <span></span> followed by a <textarea>< ...

Converting strings into time formats in MongoDB

My string appears as follows: schedule_time = { start_time : "13:00", end_time : "14:10" } Now I need to convert it into time in MongoDB. I attempted using dateFromString but encountered some issues. The aggregation query: db.getCollection('appoi ...

Accessing an array outside of an Ajax call that was initiated within a success callback

I have a CSV parsing function written in JavaScript that extracts movie names from a CSV file using an Ajax call within a loop. movies = new Array(); for (var i = 1; i < allData.length; i++) { var mName = allData[i][0]; var mPath = allData[i ...

Is it considered good or bad practice to use plain JavaScript objects in an AngularJS application?

Imagine needing a custom object that doesn't rely on AngularJS (such as a specific collection with unique functionalities). You could create it independently of AngularJS and simply use it in services/controllers. Alternatively, you could design it a ...

Establish individual states for every dynamically created component using the same handler function

I have a component in React built with Material UI, where the child component (Paper) is dynamically generated depending on the number of items in an array. The challenge I'm facing is changing the elevation property of the Paper component when it&ap ...

Combine array in MongoDB containing nested documents

I need assistance with querying my MongoDB database: Specifically, I want to retrieve data that is nested within an array and filter it based on a specific key within the nested structure. The example document looks like this: [ { "name": ...

What is the proper method for submitting a mail form via AJAX without using jQuery?

Currently, I am working on integrating a PHP mail form with AJAX. The aim is to create a straightforward form that collects user information such as phone numbers and sends it to my email address. While I have managed to set up the form to send emails usi ...

Tips for preventing Chrome from masking the background image and color on an autofill input

Google Chrome Browser has caused the background-color and background-image effects to be removed from the Username and Password input fields. Before autocomplete https://i.stack.imgur.com/Ww7Hg.png After autocomplete https://i.stack.imgur.com/hbG2C.png ...

Creating a script to open multiple URLs in HTML and JavaScript

Currently, I am working on creating a multiple URL opener using HTML and JavaScript. However, I have encountered an issue where HTTP links are opening fine but HTTPS links are not. Can someone provide assistance with this problem? Below is the code snippet ...

Oops! Hardhat Test Error "Error: Virtual Machine Exception occurred while processing transaction: reverted with reason 'Please deposit additional funds'."

Encountering an issue with the following error message: Error: VM Exception while processing transaction: reverted with reason string 'deposit more' in the Hardhat Test.js file Test.js -> it("should be able to withdraw if no one appl ...

Discovering Unconventional Columns Through Sharepoint REST Api Filtration

I am working on recreating SharePoint's front end in my app and want to add columns to my table just like a user would in SP. The challenge I am facing is determining which columns were custom generated by the user rather than standard ones. Although ...

When using the jQuery datepicker with the minDate set to 0, any past dates entered in the text box will be automatically reset to the current date

How can I prevent users from selecting past dates in a jQuery datepicker, while keeping any existing past dates displayed as is? My current code looks like this: $("#t1").datepicker({ minDate:0 }); And the text box code is, <input type="t1" va ...

Creating a JavaScript function using jQuery to calculate the total sum of textboxes with two specified classes

I'm currently attempting to calculate the total of a group of textboxes by utilizing jquery. Each textbox is styled with a class (class1) using bootstrap. To execute the jquery function, I've added an extra class (class2). Below is an example of ...

The style of the button label does not persist when onChange occurs

Encountered an interesting issue here. There is a button designed for selection purposes, similar to a select item. Here's the code snippet: <button class="btn btn-primary dropdown-toggle" style="width: 166%;" type="button" id="dropdownMe ...

The error message displayed reads as follows: "topojson has encountered a TypeError: Unable to access the property 'feature' as

Context A problem has arisen with JavaScript when trying to use the topojson.feature(topology, object) function. It seems that this issue appeared after moving from TopoJSON version 1.6.26 to version 2.x, although the functionality remains similar. The p ...