Query CSS to target an empty array within the .data() method

I have a scenario where I am storing an array in a button using Jquery's .data() method.

If the array happens to be empty, I want the button to appear in red color.

How can I target the button with an empty array using CSS?

var values1 = [];
var values2 = ['not', 'empty'];

$('.button1').data('values', values1);
$('.button2').data('values', values2);
button[data-values='[]'] { // THIS IS INCORRECT
  color: red;
}
<button class="values1">Hello1</button>
<button class="values2">Hello2</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №1

Jquery doesn't store data in attributes. It uses an external expando object to prevent memory leaks in older browsers and various serialization/deserialization issues.

If you need to store data in the DOM, it is recommended to use the attr method instead. However, reconsider your approach to styling, such as adding a semantic class instead.

var values1 = [];
var values2 = ['not', 'empty'];

$('.values1').attr('data-values', JSON.stringify(values1));
$('.values2').attr('data-values', JSON.stringify(values2));
button[data-values='[]'] {
  color: red;
}
<button class="values1">Hello1</button>
<button class="values2">Hello2</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №2

Your code had a few errors. Firstly, your JavaScript was attempting to modify buttons with the class button1 and button2, but the buttons actually had the class values1 and values2.

I prefer using the .attr() function from jQuery to add attributes, as I've encountered issues with attributes not being added when using .data(). I reserve .data() for retrieving data attributes.

Make sure to stringify your arrays before inserting them into HTML attributes.

var values1 = [];
var values2 = ['not', 'empty'];

$('.button1').attr('data-values',JSON.stringify(values1));
$('.button2').attr('data-values', JSON.stringify(values2));
button[data-values='[]'] {
  color: red;
}
<button class="button1">Hello1</button>
<button class="button2">Hello2</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №3

To handle an empty array, simply use an if condition. See the example provided below for guidance and assistance.

.btnEmpty{
        color: red;
    }

    if (values1.length === 0) {
            $('button').addClass('btnEmpty');
        }else{
            $('button').removeClass('btnEmpty');
        }

If you need to check both variables using the logical OR operator in the if condition.

if (values1.length === 0 || values2.length === 0) {
        $('button').addClass('btnEmpty');
    }else{
        $('button').removeClass('btnEmpty');
    }

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

Build.js.erb requesting a partial script task

Struggling to make my create action function accurately in my rails app. The following two lines work as intended: $('#pit_form').remove(); //remove form $('#new_link').show(); //show new link again They successfully remove the form ...

The burger icon in the navigation bar is malfunctioning, showing just a single horizontal line instead

I've been working on creating a responsive layout button that resembles the following design: https://i.sstatic.net/v5vDd.png However, I've encountered an issue where I can't seem to generate all three horizontal lines, only one of them. T ...

Issue: Inability to scroll on div overflow section

My website consists of one static page with an HTML and CSS file. Oddly enough, when testing the page and inputting content into a multiline textarea until it overflows, the browser fails to display a scrollbar. Despite inspecting the div with the id &apos ...

Navigate to a different page using a sliding transition

Currently, I am working on a project using jquery-mobile where I need to redirect to another page after clicking on an image with a delay. This is what I have done so far: setTimeout(function(){ window.location.href = "myPage.html"; }, 1000); While t ...

Having trouble accessing the input class with jQuery

When I click the "Reset To Default Settings" button in my form, I want to clear the default colors in my 4 color pickers. Each of them has an input type text field with the class anyicon-form-colorpicker. To achieve this, I locate the <a> tag and use ...

how to protect your javascript and php code

I have a question about "injection", specifically javascript injection which I find confusing. Suppose I have a javascript function that sends an AJAX request to get a user's permission level, and then uses an if statement to assign power based on th ...

What is causing the floated element to overlap the element below instead of vice versa?

div { background-color: #00FFFF; } p { width: 50px; height: 50px; border: 1px solid black; margin: 0px; } #p1 { background-color: red; float: left; } #p2 { background-color: green; } #p3 { background-color: orange; } #p4 { backgr ...

A dynamic Angular search box designed for filtering columns in a table

I have a functioning table code that displays data related to domains: Now, I would like to enhance this table by adding a dynamic search box specifically for filtering the column named domain. As the user types in new characters in the search box, the ta ...

Attempting to retrieve information from my MongoDB database and populate it into a <table> structure on a web page

My objective is to extract data from a MongoDB database and display it in an HTML table. Specifically, I am trying to retrieve information from the hangman database's players collection, which contains fields for name and score. Can anyone help me ide ...

The 'propTypes' property is not found on the 'typeof TextInput' type declaration

Trying my hand at creating a react-native component using Typescript for the first time, but I ran into an issue on line 51: Property 'propTypes' does not exist on type 'typeof TextInput Couldn't find any helpful information on similar ...

A problem occurred while compiling the 'SharedModule' template: The expression form is not compatible with the current system

In creating this share module, I have included the following components: @NgModule({ declarations: [ , DateToPersian , EnumToArrayPipe , SearchWtihInput , ConvertbytePipe , ArraySortPipe , MonySplitePipe , IsEllipsisActiveDir ...

Sometimes the data-autoplay feature does not function properly in jQueryfullPage.js

I am in the process of developing an HTML page using jQueryfullPage.js. Within this page, I have incorporated 17 videos across 17 different sections. These videos are presented as YouTube iframes with a data-autoplay attribute. Overall, everything is fun ...

The expandable row remains open even after filtering the table with JavaScript

An expandable row in the table displays details of rows. I have implemented a JavaScript search and filter function to find specific row content. However, when using the search filter, it successfully shows results but does not expand the details as intend ...

Error: The module PosModel is not defined

Recently, I took over the responsibility of working on the models.js file for the point_of_sale module. My task was to add a new model by integrating the following code: openerp.dewieuw = function(instance, local) { //module is instance.point_of_sale var ...

Using the integrated pipeline mode in IIS is necessary for this operation to be

My aspx page has an ajax call which looks like this: $.ajax({ url: "/SiteAdmin3/UpsIntegration.aspx/addUpdatePackageData", data: JSON.stringify({ '_OrderNumber': $("#txtOrderNumber ...

Using jQuery in CodeIgniter for form validation and AJAX form submission is an effective way to ensure

Whenever I submit the form, errors show perfectly. However, when I submit it again, the data enters the database but the else condition does not work as expected. I want to hide the form and display a success message. The first time, an error response occ ...

Don't delay in fulfilling and resolving a promise as soon as possible

Currently, I am facing an issue with a downstream API call that is returning a Promise object instead of resolving it immediately. This is how I am making the downstream call: const response = testClient.getSession(sessionId); When I console.log(response ...

"Encountering a Challenge with Setting Up Forms on

I've recently started learning to code and I'm facing an issue with my form appearing stretched out. You can view it here: I initially thought it was due to margins, so I increased them. Then, I tried adjusting the width to 50%, but that didn&ap ...

Incorporating an image into a list of checkboxes post-connection

Looking for a way to populate a checkbox list through datasource/databind and then integrate an image with each checkbox? I can do both separately but struggling to combine them successfully. My task is to create a checkbox list of students for teachers t ...

The server encountered a 500 Internal Server Error because it could not read the 'username' property of an undefined object

When attempting to register a user in a mongodb database using express, a POST call was made to localhost:3000/users/register The request body included: { "firstName": "Jason", "lastName": "Watmore", "username": "jason", "email": "<a ...