Capture selected items from checkboxes and incorporate them into the CSS styling

I would like to give users the ability to choose from a series of checkboxes with additional options to add to their CSS.

Using JavaScript, I am searching for checked boxes, extracting their names, adding them to a list, and then inserting that list into CSS as a value for a property.

I'm unsure if it's being inserted incorrectly into the CSS or not being added at all.

$(document).ready(function () {

  var checkbox = document.querySelector('[type="checkbox"]');

  checkbox.addEventListener('change', function() {
      getOTFeaturesTextA();
  });
});

function getOTFeaturesTextA(){

  var textA = document.getElementById("textA"),
    chkArray = [];

  $(".ot-textA:checked").each(function() {
    chkArray.push($(this).val());
  });

  var selected;
  selected = chkArray.join(',') ;

  if(selected.length > 0){
    textA.css("font-feature-settings", selected + ", liga");
  }else{
    textA.css("font-feature-settings", "liga");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ot-checkboxes">
  <p>
    <label>
      <input type="checkbox" name="frac" value="'frac'" class="ot-textA" id="frac">
      Fraction</label>
    <br>
    <label>
      <input type="checkbox" name="aalt" value="'aalt'" class="ot-textA" id="aalt">
      Alternatives</label>
    <br>
        <label>
      <input type="checkbox" name="onum" value="'onum'" class="ot-textA" id="onum">
      Oldstyle Numbers</label>
  </p>
</div>
<div id="textA" contenteditable="true"><span>Trying out checkboxes 3/4 </span></div>

Answer №1

To solve this issue, opt for style rather than css

textA.style['font-feature-settings'] = selected + ", liga";    

Answer №2

After reviewing your example code, I've implemented some modifications:

  • Eliminated the quotes from the checkbox values.
  • Implemented a single change listener on the container element for the checkboxes instead of individual listeners for each checkbox.
  • Since "liga" is supposed to always be present, I set it as the initial item in the array instead of checking if other features are selected first.

I considered your familiarity with ES6 features while coding this example to align with your preferred style. There may still be opportunities for further optimization or alternative approaches.

$(document).ready(function () {
  var checkboxContainer = document.getElementById('ot-checkboxes');
  
  if (checkboxContainer !== null) {
    checkboxContainer.addEventListener('change', getOTFeaturesTextA);
  }
});

function getOTFeaturesTextA(){
  var 
    textA = document.getElementById("textA"),
    selectedFeatures = document.querySelectorAll('.ot-textA:checked'),
    features = ['"liga"'];

  selectedFeatures.forEach(function(selectedFeature) {
    features.push('"' + selectedFeature.value + '"');
  });

  textA.style.fontFeatureSettings = features.join(',');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ot-checkboxes">
  <p>
    <label>
      <input type="checkbox" name="frac" value="frac" class="ot-textA" id="frac">
      Fraction</label>
    <br>
    <label>
      <input type="checkbox" name="aalt" value="aalt" class="ot-textA" id="aalt">
      Alternatives</label>
    <br>
        <label>
      <input type="checkbox" name="onum" value="onum" class="ot-textA" id="onum">
      Oldstyle Numbers</label>
  </p>
</div>
<div id="textA" contenteditable="true"><span>Trying out checkboxes 3/4 </span></div>

Answer №3

One important thing to note is that there is no such function as .css() in vanilla JavaScript. Consider using .style or switching to jQuery for element manipulation instead.

function getOTFeaturesTextA(){
    const textA = $("#textA");
    const chkArray = [];

    $(".ot-textA:checked").each(function() {
        chkArray.push($(this).val());
    });

    const selected = chkArray.join(',');

    if(selected.length > 0){
        textA.css("font-feature-settings", selected + ", liga");    
    }else{
        textA.css("font-feature-settings", "liga");
    }
}

Important: It's recommended to avoid using var and refrain from declaring variables in a single line whenever possible. If you are going to use a variable immediately after declaring it, there's no need to initialize it as empty.

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

Filtering the data in the table was successful, but upon searching again, nothing was found. [Using Angular, Pagination, and

Having a table with pagination, I created a function that filters the object and displays the result in the table. The issue arises when I perform a new search. The data from the initial search gets removed and cannot be found in subsequent searches. Bel ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

What is the best way to create an animation where every letter in a word transitions to a different

Is there a way to animate a word so that each letter changes color within a range of 7 colors, with all letters displaying different colors simultaneously in an infinite loop? <div class="box"> <h1 class="logo animate__animated an ...

How does Socket.io facilitate a basic web socket connection with a specific URL?

My current project involves a client making a WebSocket request to the following URL: ws://localhost:3000/feed/XBTMUR https://i.sstatic.net/R7H9T.png On my server side, I am utilizing NodeJs with express running. I have decided to implement Socket.io in ...

What could be the reason for the component failing to update even after modifying the object's properties?

I have come across some related threads on Stack Overflow, but they only briefly mention using the spread operator. But why should we use it? In the code below, I am trying to update the firstName property of the user object, which is a state, when clicki ...

Guide on automatically filling input text fields with database values when a checkbox is clicked

I need to automate the process of filling in multiple input text fields with values from variables retrieved through a SELECT query when a checkbox is clicked. For instance, if the SELECT query returns the Warehouse Street Address ($WarehouseStreetAddres ...

Utilizing JQuery to link keyboard inputs with function triggers

Is there a way to detect when a keyboard key is pressed and then execute this line of code? $('#submit_p').on('click',function(event){...} Appreciate it. ...

The browser prevented the script located at “http://127.0.0.1:5500/assets/platform.png” from loading due to an invalid MIME type of “image/png”

Sorry if this question seems repetitive, but despite extensive searching, I haven't been able to find a solution to my specific problem. I am currently working on developing a basic JavaScript game, but I'm facing challenges when it comes to impo ...

How can I extract the URL from the event listener in Cordova's in-app browser event and then automatically close it once a specific URL is reached?

In my journey with ionic version 1 (just starting out with ionic & angularjs), I encountered an issue while trying to close the in app browser upon reaching a specific URL. The problem arises from the fact that the event triggered on "loadstart" is o ...

Upon successful registration, users will be automatically redirected to their profile page

Having trouble with the redirection to the login page from my profile page, which is an HTML file and the main page is the login page. I've tried redirecting to both pages, but it always lands in the catch block whenever a redirect is attempted. angu ...

X-Ray Rendering in Three.js and Webgl

Looking to create an x-ray effect in three.js / webgl. Something like this: UPDATE I am seeking help on how to achieve a real-time render with the x-ray effect, instead of just a static image. This can be accomplished using shaders that modify density i ...

The style attribute transforms the background-image url quotation to become &quot;

I'm currently working on creating a catalog component that will allow me to display images, titles, and descriptions multiple times. Below is the code for this component: import React from "react"; import '../pages/UI.css'; import ...

Effective ways to enable users to upload files in a React Native app

Being in the process of developing a react native app, I am faced with the challenge of allowing users to easily upload files from their mobile devices (pdf, doc, etc). Unfortunately, my search for a suitable native component has proven fruitless. Can anyo ...

What is the best way to specify attributes such as font size and padding for the mobile version in AMP for email?

I attempted to utilize media queries to create a responsive AMP email, but it seems that this feature is not supported in AMP. However, I discovered that you can define media="(max-width: 599px)" and media="(min-width: 600px)" for </amp-img>, but the ...

Leveraging JavaScript Functions in HTML

I am having an issue with a JavaScript file containing two similar functions that are executed through an HTML form. While the first function runs smoothly, the second function does not display correctly. It seems like I might be calling or executing the ...

Are there any guidelines or rules outlining what is still considered valid JSONP?

I am looking for information on how to properly parse JSONP messages in .NET and extract the JSON data they contain. Is there a current specification that outlines what constitutes a valid JSONP message? During my research, I came across a blog post from ...

How does the "deliver_order" function retrieve the value of the name parameter?

function take_order(name, callback1) { console.log("order has been taken."); callback1(name); } function prosess_order(name, callback2) { console.log(`prosesing order for ${name}.`); callback2(name); } function deliver_order(name) { console.log ...

Invoking PHP code from within Javascript will output the function as a direct string

I seem to be going in circles and missing something silly... My setup involves using CodeIgniter on the server-side and Bootstrap on the client, but that's not really the issue here... I am attempting to access a PHP value within a JavaScript functi ...

CSS code completion in PhpStorm is not functioning properly for Twig extended templates

Currently, I am working with PhpStorm 2016.1 and facing an issue with file autocomplete. The scenario is as follows: @mycss .style {color : red} @base.html.twig [...] <link rel="stylesheet" href="/vendor/mycss.css" /> <!--HERE AUTOCOMPLETE OF s ...

Verify the response retrieved from the ajax call and conduct a comparison

I'm struggling with the following code. Whenever I submit a form, I want to display a modal view. The modal view is functioning correctly, but it keeps showing the same one every time I submit. The #status1 returns a modal view with success markup a ...