How can you use jQuery to take the input value and assign it as a class to the label surrounding it?

I need a simple solution: how can I retrieve the input value and apply it as a class to the same input? For example, I want to extract the value "gray" and add class="gray" to the surrounding label in order to style the label text that says "Gray".

This is the structure:

<li>
<label>
<input type="radio" id="acf-field" name="acf[field_5af32dbd01019]" value="gray"/>Gray
</label>
</li>

<li>
<label>
<input type="radio" id="acf-field" name="acf[field_5af32dbd01019]" value="green"/>Green
</label>
</li>
<li>

Using

$("li label").each(function() {
var $link = $(this).find("input").val();

will fetch each value, but how can I use .addClass to append a class to the enclosing label like this: <label class="gray">

The link below includes an answer on adding the class to the parent label: https://jsfiddle.net/j08691/qnzpahrq/

$("li input").each(function() {
      $(this).parent().addClass($(this).val());
})

Answer №1

To achieve this, you can use the following code snippet:

$("li input").each(function() {
      $(this).addClass($(this).val());
})

$("li input").each(function() {
      $(this).addClass($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <label>
<input type="radio" id="acf-field" name="acf[field_5af32dbd01019]" value="gray"/>Gray
</label>
  </li>

  <li>
    <label>
<input type="radio" id="acf-field1" name="acf[field_5af32dbd01019]" value="green"/>Green
</label>
  </li>
</ul>

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

The jQuery message validator is currently experiencing some issues with its functionality

I am working on implementing a basic login system using jQuery and it appears to be functioning correctly, but I keep getting an error message in my jQuery code here: alert('Error in system');. What's puzzling is that when I use alert(answe ...

Transforming the header to function similarly to the address bar in the Google Chrome mobile app

I have managed to create a fixed header that appears when the user scrolls up and disappears when they scroll down. However, I want it to behave like the address bar on the Google Chrome mobile app - remaining stationary until the top of the window reaches ...

Creating a webpage that utilizes varying headers for each section can help to

When trying to print a multi-page webpage, I encounter an issue with the headers. How can I ensure that different headers appear on each page after the first one? Specifically, my problem arises when a label on the first page spans across to the second pa ...

Setting the width of an image within an iframe: A step-by-step guide

Is there a way to adjust the width of an image within an iframe? Typically, if an image with high resolution is placed inside an iframe, the iframe becomes scrollable by default. ...

Foreground spotlight shines upon background button display

Apologies for any language barriers... I'm currently working on developing an E-commerce Website. The issue I am facing is that when I click the Add to Cart (Zum warenkorb hinzufügen) button and the window pops up with the + and - icons, they are v ...

Avoid injecting JavaScript code into an element with AJAX to prevent unnecessary loading times

Scenario Overview I am utilizing ajax to validate a user-filled form. When the user clicks the submit button ("External Script"), the PHP/JavaScript function checks the input fields and if an error is found, it inserts an error message into a predefined & ...

How can you incorporate a specific CSS file based on conditions in Angular?

What is the method for selectively applying CSS files in Angular? It is required to have several CSS files and apply them to an Angular component based on a condition. What are the various approaches available to achieve this? Any method can be considere ...

Customizing the background color of an option using HTML and CSS

I am currently developing an option form where each selection will appear in a different color as the user scrolls down. Once a selection is made, it should be saved and displayed with the chosen color. https://i.sstatic.net/gvdpt.png My goal is to save ...

Using the click() event to evoke FancyBox

How can I make a FancyBox overlay appear when a DIV is clicked? I have searched for ways to trigger FancyBox through an Anchor click, but none of the solutions address my specific situation. I need to use a DIV instead of an Anchor because my clickable ov ...

Is there a way to style CSS Content to appear both italicized and bold?

As I work on my project, I am aiming to style the CSS content class in both italic and bold formats. Take a look at the code snippet below. div::before { content: "text"; color:black; } <div></div> My goal is to achieve this exclu ...

A step-by-step guide on incorporating RAW css into your Jekyll website

I am experiencing an issue with loading a CSS file on my website. <link rel="stylesheet" href="/assets/css/my_file.css"> This file is located at _assets/css/my_file.css. However, when I try to load the page, the CSS file does no ...

Disable, Hide, or Remove Specific Options in a Single Dropdown Selection

A challenge I am facing involves creating a form with multiple select options that need to be ranked by the user from 1-8. However, I am encountering some difficulties in hiding, removing, or disabling certain select options. Below is an excerpt from my f ...

A guide on using jQuery to include an icon within a select option

I'm having trouble adding an icon to a select dropdown using jQuery. I attempted to include the icon within the option itself, but it displays as empty boxes. Additionally, I want the selected option's icon to appear above without the accompanyin ...

Choosing a value using Jquery on change is not effective

NOTE: Unnecessary information has been removed I am looking to select the parent element when the value of a select element is changed, and then serialize that parent: jQuery('body').on('change','.shop_table select',function ...

Achieving full coverage of cell content within a cell area by utilizing align-items in CSS Grid

Is it possible to achieve two conflicting goals using CSS Grid? In my design, I want the content in each cell to be vertically centered using align-items: center; At the same time, I need the entire area of the cell to be filled with color. However, ...

After attempting various solutions for days, the navbar was finally switched to a vertical layout following the addition of the Bootstrap Carousel, although functionality

After adding the Bootstrap carousel to my index.html, the navbar unexpectedly switched to a vertical layout. I tried adjusting various elements such as font size and width, but it seems like the issue lies within the carousel itself. Whenever I include th ...

What is the best way to align a dialog box on a screen?

I'm having an issue with the positioning of my dialog box - it always appears in the upper left corner when I want it to be centered in the middle. Can anyone provide guidance on how to achieve this? Below is my script code: $(function() { $("#c ...

What is the best way to update an existing array with a new array following an AJAX call?

I currently have a collection of 3 objects stored in an array. Recently, I initiated an ajax request to fetch a brand new array to substitute the current one. console.log('initiating process'); console.log(existingData); jQuery.ajax({ url: ...

The Ajax request did not provide the desired outcome

My current challenge involves using ajax to request an image from an external URL. I can successfully achieve the desired result by using return(url), but I am encountering issues when attempting to do so through a promise. Despite logging the url and ge ...

Is there a way to decrease the speed of a text when hovering over it?

Is there a way to create a button that displays text before another text only on hover, with a delay? I've managed to achieve the effect but can't figure out how to slow it down. For example, notice how quickly the word "let's" appears when ...