Styling elements with values from an object array

I have been working on a code snippet to extract checked checkboxes and match their names with an object array in order to retrieve certain values. You can find a sample fiddle here.

Now, I am wondering how I can utilize these extracted values to dynamically create a span element, update its color, and position it based on the checkboxes that are checked.

      var inputElements = document.getElementsByName("fruits"); 
      const item = { 
            "lychee" :{ price:10, pos:80, colCode:'ff0000' }, 
            "orange" :{ price:12, pos:60, colCode:'00ff00' },
            "apple"  :{ price:8, pos:40, colCode:'ff6600' },
            "mango"  :{ price:12, pos:60, colCode:'00ff00' },
            "banana" :{ price:4, pos:80, colCode:'ff0000' }
       };
    
      let result = [...document.querySelectorAll("[name=fruits]:checked")]
      .map(chk => (
          var marker = document.createElement('span');
          marker.style.color = colCode:${item[chk.value].colCode}, //this does not seem to work
          marker.style.marginLeft = pos:${item[chk.value].pos}px ) //this also does not work
      );
    <input type="checkbox" name="fruits" value="lychee">Lychee <br> 
    <input type="checkbox" name="fruits" value="orange" checked>Orange <br>
    <input type="checkbox" name="fruits" value="apple">Apple <br>
    <input type="checkbox" name="fruits" value="mango" checked>Mango <br>
    <input type="checkbox" name="fruits" value="banana">Banana

Answer №1

Your query lacks clarity regarding the intended outcome of your code, but fret not! I am here to assist you in resolving any syntax errors that may be present.

The issues with your code are as follows:

  • The arrow function is not being utilized correctly. If multiple statements or variable definitions are needed, braces should be used followed by returning the desired result.

  • Template literals are not being implemented properly. To effectively use them, they must be enclosed within backticks.

var inputElements = document.getElementsByName("fruits");

const item = { 
    "lychee": { price: 10, pos: 80, colCode: "ff0000" }, 
    "orange": { price: 12, pos: 60, colCode: "00ff00" },
    "apple": { price: 8, pos: 40, colCode: "ff6600" },
    "mango": { price: 12, pos: 60, colCode: "00ff00" },
    "banana": { price: 4, pos: 80, colCode: "ff0000" }
};

let result = [...document.querySelectorAll("[name=fruits]:checked")].map(chk => {
    /* Create a <span> element. */
    var marker = document.createElement("span");
    
    /* Set the properties using template literals. */
    marker.style.color = `#${item[chk.value].colCode}`;
    marker.style.marginLeft = `${item[chk.value].pos}px`;
    
    /* Put some content into the <span>. */
    marker.textContent= "Content";
    
    /* Append the <span> into the wrapper. */
    wrapper.appendChild(marker);
    
    /* Return the <span> so that it's cached inside the results array. */
    return marker;
});
<input type="checkbox" name="fruits" value="lychee" checked>Lychee <br> 
<input type="checkbox" name="fruits" value="orange" >Orange <br>
<input type="checkbox" name="fruits" value="apple" checked>Apple <br>
<input type="checkbox" name="fruits" value="mango" checked>Mango <br>
<input type="checkbox" name="fruits" value="banana">Banana

<div id = "wrapper"></div>

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

Guide to using jQuery to load an image

I am using this code to load an image and display it within a dialog box. <div id="image_preview" title="Client Photo Preview"> <p><img src="" alt="client image" id="client_image_preview" /></p> </div> $("#client_image_p ...

JavaScript can sometimes present peculiar challenges when it comes to setting style attributes, especially when a DOCTYPE is

It seems like I am encountering an issue when trying to dynamically create and modify a <div> element using JavaScript. The problem arises when I use the XHTML 1 Transitional doctype. This is how I am generating the <div>: var newDiv = docume ...

What could be causing the malfunction of material-UI Tabs?

My Material UI Tabs seem to have stopped working after a recent update. I suspect it may be related to the react-tap-event-plugin update I installed. Initially, I thought it was due to tab indexing but even using values like value='a', value=&apo ...

Key Enhancements for Functional Stateless Components

How can I accurately assign a key in a functional component, specifically using the 'key' keyword instead of just a general index? I am attempting to use Map in a functional component to generate a list of another element. However, when I try to ...

What is the best way to access a document that has the lang attribute set to "en" using JavaScript?

I am working on implementing conditional styling in JavaScript by referencing this line of code located before the opening <head> and <body> tags: <html class="js" lang="en"> I want to set a condition so that if the l ...

What is the best way to incorporate this locale variable into the primary script?

Is it possible to access the locale variable from the main script and convert it into a global variable? The current method I tried does not seem to be working. Any advice or guidance is appreciated. //Converting a local variable to a global variab ...

Encountered a 404 error while attempting to build and serve a Vue.js project using 'npm build' in Apache Tomcat

After setting up a Vue.js project, the configuration in the package.json file looks like this: "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": ...

What is the best method for extracting span text using selenium?

<p id="line1" class=""><span class="bot">Do you have a short-term memory?</span><span id="snipTextIcon" class="yellow" style="opacity: 1;"></span></p> I want to extract this text: Do you have a short-term memory? This ...

PWA notifications not working on iOS with FCM even after multiple tries

I am currently utilizing Firebase Cloud Messaging in order to send daily notifications to iOS users who have installed a PWA app. Upon testing, I noticed that each token is limited to receiving only 2 notifications successfully. Any attempt beyond that w ...

Create a WebGL object remotely on the server

Exploring potential project ideas, I was curious to see if it's feasible to produce a WebGL scene or object on the server side and then have it rendered on the client. The motivation behind this is that generating a scene typically involves utilizing ...

In what scenarios is it most beneficial to utilize an isolate scope in Angular?

The AngularJS guide states that the isolate scope of a directive isolates everything except models explicitly added to the scope: {} hash object. This is useful for building reusable components because it prevents unintended changes to your model state, al ...

Monitoring Unread Message Totals in Twilio Chat

Seeking an efficient method to retrieve and update the count of unread messages in Twilio chat. I have explored similar questions and answers on other platforms, such as this one, which suggested looping through the Channel's array and utilizing Messa ...

Encountered an issue while trying to access the length property of an undefined value within an aside

I am currently utilizing ng-strap's modal, alert, and aside features. Each of them is functioning properly on their own, but when I attempt to place an alert or modal inside an aside, it throws the following error: Uncaught TypeError: Cannot read p ...

What is an alternative method to trigger a Bootstrap modal without using jQuery or bootstrap.js JavaScript code?

I am currently developing a survey application that is designed to be extremely lightweight. This application is specifically tailored for use in third world countries where internet connection is very limited. After conducting some research, we discovere ...

One-of-a-kind browser identification for users, no login required

I have an online boutique and I want to enable customers to make purchases without creating an account. To achieve this, I need a way to associate a selected list of items with a user. Initially, I considered using the IP address for this purpose but fou ...

Issues with Leaflet's MaxBounds functionality - boundary constraints not functioning as expected

I recently experimented with Leafletjs maxBounds by testing it out using code from Mapbox's example. For my complete code, you can also view it on this jsfiddle link. <!DOCTYPE HTML> <html> <head> <title>leaflet bounds te ...

tips for converting objects into arrays with JavaScript

I have an object and I would like to convert it into an array const object1 = { a: { hide:true}, b:{} }; I am currently using Object.entries to perform the conversion, however, I am struggling with understanding how it should be done. Object.entries ...

What is the best way to conceal elements that do not have any subsequent elements with a specific class?

Here is the HTML code I have, and I am looking to use jQuery to hide all lsHeader elements that do not have any subsequent elements with the class 'contact'. <div id="B" class="lsHeader">B</div> <div id="contact_1" class="contac ...

Is there a way to incorporate a custom method into a JQuery tab widget?

Need assistance with extending the functionality of the jQuery UI tabs widget by implementing a new method for all instances. Attempted using both $.extend() and jQuery.widget(), but encountered an issue where the newly added method remains undefined when ...

Transform the C# DateTime to LocalTime on the client side using JavaScript

Utilizing the Yahoo API on my server to retrieve currency information can be done through this link: Yahoo Currency API This API provides me with both a Date and a Time, which I'd like to combine into a single DateTime object. This will allow me to e ...