Utilizing JavaScript for manipulating arrays and displaying images

After asking this question previously without a satisfactory solution, I am hoping to provide better clarification. Imagine having an array with 3 items and it lands on 0 - a code is set up to display this in a div. Now, I want the image to be shown right next to the displayed array. For instance, if the array consists of BMW, Civic, and Mercedes, and a random number generator selects 1 (BMW), the word will appear in the div and a BMW logo should appear next to it. The same goes for Civic and Mercedes, each having their respective logos displayed alongside their names. Additionally, I would like to add IDs so that CSS background images can be easily added according to the picture's design.

Answer №1

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Car Selector</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

  <ul id="carList">


  </ul>

  <button id="getRandomCar">Get Random Car</button>


</body>
  <script>
    $(document).ready( function(){
    var vehicles = [{
     brand : 'Toyota',
     logo : 'toyota-logo.png',
     model : 'Camry',
    },
    {
     brand : 'Ford',
     logo : 'ford-logo.png',
     model : 'Mustang',
    },
    {
     brand : 'Chevrolet',
     logo : 'chevy-logo.png',
     model : 'Silverado',
    }];

function randomNumGen(limit) {
  return Math.round(Math.random()*limit); 
}

function displayRandomCar() {
  $('#getRandomCar').click( function() {

    var carIndex = randomNumGen(vehicles.length - 1);
    console.log(carIndex);
    var template = '<li>';
    template += 'Brand: ' + vehicles[carIndex].brand + '</br>';
    template += 'Logo: ' + vehicles[carIndex].logo + '</br>';
    template += 'Model: ' + vehicles[carIndex].model + '</br>';

    $('#carList').html(template);

  } );
}
        displayRandomCar();
    });
  </script>
</html>

For more details, visit this link.

An array of objects (vehicles) has been created to store different car information.

The script generates a random number to select a car from the vehicles array and displays its details in the DOM.

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

Running two blocks of scripts (utilizing lab.js as a loading manager)

I am currently facing an issue where I am trying to load two separate blocks of `lab.js` in different locations. However, when I attempt to utilize functions from the second block that are called from files loaded in the first block, they are showing as un ...

Idiosyncratic TypeScript behavior: Extending a class with comparable namespace structure

Lately, I've been working on creating a type library for a JavaScript written library. As I was defining all the namespaces, classes, and interfaces, I encountered an error TS2417 with some of the classes. I double-checked for any issues with method o ...

To optimize your bundling process, include the leaflet.css file from the node_modules/leaflet directory using webpack

Currently, I am working on developing a map application using webpack and leaflet. While I can successfully require leaflet.js from my map.js file, I encounter an error when trying to call leaflet.css. The configuration in my webpack.config.js is as follo ...

Is there a way to use the property of an object to perform a merge sort, rather than relying on an Array?

Query About Sorting JSON Object in JavaScript In search of the most efficient method to sort a large JSON object based on a specific property, I turned to JavaScript. My initial thought was to utilize a merge sort algorithm for this task due to its speed. ...

Promise.all does not wait for the inner Promise.all to complete before continuing

let dataObj = [ { Id: 1, name: 'Alice', Address:[{ city: 'Paris', country: 'France' }] }, { Id: 2, name: 'Bob', Address: [{ city: 'NYC', country: &a ...

Incorporating JSON data into an HTML table

Looking to populate an HTML table with JSON data, but struggling with parsing and appending the data correctly. Can anyone provide guidance or assistance? <!DOCTYPE html> <html> <head> <title>JSON Demo</title> < ...

Experiencing difficulties when trying to pan and zoom the data obtained from d3.json within a line chart

I am currently working on developing a trend component that can zoom and pan into data fetched using d3.json. Here is the code I have written so far: <script> var margin = { top: 20, right: 80, bottom: 20, left: 50 }, width = $("#trendc ...

What could be the reason behind Next.js attempting to import a non-existent stylesheet?

Lately, I've come across an issue where Nextjs is attempting to import a non-existent stylesheet (refer to the images below). I'm looking for guidance on how to resolve this error. Hoping to find a solution here, thank you Web browser console W ...

The createElement function in Vue.js does not always return a fully formed component

There is a scenario where I need to create a functional component for a specific purpose. The task at hand involves taking all the children elements and adding some additional props to them, but only to those that are custom components of type ChildCompone ...

Are personalized URLs necessary for jump anchor links?

When utilizing 'Jump to' or 'Anchor' links to navigate to a different section of a webpage, should I include a canonical URL or use a 'no-follow' link for SEO optimization? Is it significant at all? And if so, which approach i ...

The concatenation of Ajax results appears to append to the existing data

My ajax function handles uploading comments to a form, which then returns the same string. If successful, the comment is added to a comment box and the input text is cleared. The issue arises when a user adds another comment; the new comment is appended w ...

Using XSLT with JavaScript

I am currently working with a set of XML files that are linked to XSLT files for rendering as HTML on a web browser. Some of these XML files contain links that would typically trigger an AJAX call to fetch HTML and insert it into a specific DIV element on ...

Angular factory transforming service

I am looking to transform the 'i18n' function into a factory in order to return a value instead of just setting it. Any suggestions or tips would be greatly appreciated! services.factory('i18nFactory', function() { var language = ...

Ways to remove the address bar from a mobile browser like Chrome or an Android browser

Is there a way to make videojs go full screen on Android devices when the URL is entered, without displaying the address bar? ...

Can a website accurately identify my operating system and browser version even if my browser settings have been altered?

When using selenium to browse a website, I have modified the useragent, platform, and oscpu properties of the navigator object in my Firefox browser. Will the website be able to detect my actual operating system and browser version? ...

In order to add value, it is necessary to insert it into the text box in HTML without using the "on

example <input type="text" id="txt1" onChange="calculateTotal();" /> <input type="text" id="txt2" onChange="calculateTotal();" /> <input type="text" id="txt3" onChange="updateValue();" readonly/> <input type="text" id="txt4" onChange= ...

The alignment of flexbox within a list item is not positioned at the top as expected

When I place a flexbox inside a list item, the content is being pushed down by what seems to be a full line height. I have tried various CSS properties like setting margin-top: 0 for the flexbox, margin-top: 0 for its children, adding flex-wrap to the fle ...

What is the method to ensure an element is displayed in Selenium WebDriver?

Looking for assistance on how to choose options from a dropdown when the element is not visible and has a boolean attribute? Here's the HTML code snippet: <select id="visualizationId" style="width: 120px; display: none;" name="visualization"> & ...

Maintain text while transitioning to another page

On my webpage (refer to image for details), users need to select options through a series of steps. The process involves clicking on a link in the top box, then entering a search term in the searchbox to display relevant links in div1. Clicking on a link ...

The Gulp task is stuck in an endless cycle

I've set up a gulp task to copy all HTML files from a source folder to a destination folder. HTML Gulp Task var gulp = require('gulp'); module.exports = function() { return gulp.src('./client2/angularts/**/*.html') .pipe( ...