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

Notifying the view with a SignalR message from the controller upon event trigger

Just starting out with SignalR and attempting to set up a notification for a specific event triggered by an API. What I've attempted: Hub: public class NotificationHub : Hub { private static IHubContext hubContext = GlobalHost.Connectio ...

Execute a JavaScript function daily for each new user

Can someone help me understand how to execute a JavaScript/jQuery function that triggers a PopUp once for each new user visiting a webpage? Below is the code I need assistance with. $(window).load(function() { $('#index9').fadeIn("slow"); ...

Execute a script when a post is loaded on a WordPress page

I am looking to have my jQuery script execute every time a post page is opened or loaded. I tried using echo in the script but it did not work. Where should I place the script to ensure it runs? single.php <script src="https://ajax.googleapis.com/aja ...

Is there a way to create an event listener that responds to a simultaneous click of both mouse buttons?

Despite my extensive research on the Internet, I was unable to find any examples. Interestingly, Vue only supports right and left clicks separately which I find peculiar as it seems like a basic task that can easily be accomplished with plain Javascript. ...

What causes the variable within the useEffect function to delay its value update?

const [inputValue, setInputValue] = useState(""); const previousInputValue = useRef(""); useEffect(() => { previousInputValue.current = inputValue; }, [inputValue]); return ( <> <input type="text" value={ ...

JavaScript has encountered a syntax error

When working on an animation in javascript, I encountered a problem that I can't seem to identify. I am attempting to make the pan function work with the "mover" function, but it seems like either I am not using the properties correctly within the "tr ...

Angular 2 module transpilation services

In my angular 2 application, there is a module called common. Here is how the project structure looks like: main --app /common --config //.ts configs for modules --services //angular services --models --store //ngrx store /co ...

What could be causing my for loop to unexpectedly terminate early?

I'm currently tackling a challenge on CodeChefs: My task is to find the smallest missing positive integer in an unsorted list of numbers. Here's the code snippet I've implemented: var firstMissingPositive = function(nums) { nums.sort(); ...

I'm having trouble pinpointing the issue in my code

For some reason, the first button in the div in this code is not working on HTML files. I have tried multiple JavaScript and HTML validators but none of them seem to work. Surprisingly, it works fine on codecademy.com and w3schools.com, but the issue persi ...

An issue occurred while testing with React-Native Testing Library/Jest, where the property 'TouchableOpacity' could not be read

I am currently in the process of conducting tests using jest and react-native testing. Unfortunately, I have encountered an issue where TouchableOpacity is not being recognized and causing errors. Card.test.js import Card from "../Card" import R ...

Switch between showing and hiding a div by clicking on the panel header and changing the symbol from + to

I need assistance with a panel feature on my website. The panel should expand when the "+" symbol is clicked, displaying the panel body, and the "+" symbol should change to "-" indicating it can be collapsed by clicking it again. There is a slight twist t ...

I'm having trouble getting my Ajax edit code to function correctly. Can anyone offer some assistance?

I am currently working on a basic registration system that includes two forms: one for registration and another for selecting a city. I have encountered an issue where newly added cities update perfectly, but when trying to use the selected city in the reg ...

Regular expression for precise numerical values of a specific magnitude (any programming language)

I have been searching for a solution to what I thought was a common problem but haven't found one yet. What I need is a regular expression that will fail on a specific number of significant figures (a Max), but pass for fewer than the Max. It should ...

Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly. Here is a snippet from my app.js: import { createApp } from "vue" const app = createApp({}) // pinetree i ...

Unable to use document.write when extracting code from the internet

I am currently developing a game using emulatorjs and ruffle. The goal is to have it all contained in a single downloadable file that can be run locally. I attempted to create another file for auto-updating purposes, but encountered issues with some of the ...

Storing client time data in a database using Node.js

Just starting out with Node.js so bear with me while I learn the ropes. I successfully set up a basic TCP server using the guide here In my current project, users will connect to the server from a web browser and I'm interested in capturing the TCP ...

AngularJS OAuth authentication Pop-up: Waiting for JSON response

I am looking to initiate an oauth request in a new window for my project. Here is how I can open the new window: var authWindow = $window.open("/auth/google/signin", ""); After the callback, my server will respond with JSON data: app.get('/auth/ ...

Use the lodash chunk method to split a mapped array into two separate arrays

Looking to organize some data into tables? I have a dataset from an API that you might find helpful. [ { date: "1/11", data: [ { camera: "camera 1", count: 10 }, { camera: "camera 2", count: 20 ...

What is the best way to modify a current state object without causing an endless loop of redirects?

const useCase = (argument) => { const [value, setValue] React.useState(argument) React.useEffect(() => setValue({...value ...argument), [argument, value, setValue]) } The above code is currently causing an infinite loop due to setting the stat ...

a JavaScript file containing only a require statement with a list of dependencies and a function

I have a question regarding the implementation of the "require" statement in JavaScript. I am just starting to work with JS and Dojo, and I encountered an issue while developing a Plug-in for a website. The main Java class of the plugin makes a reference t ...