Change the HTML table's toggle element to either 'on' or 'off' based on the specified value using jQuery

I am looking to modify the appearance of an HTML/CSS/jQuery toggle element based on the value of a cell within a table, either displaying "YES" or "NO".

The required functionality includes:

  1. If the text in the table cell is "yes", the toggle element should have a class of .off and set the checked attribute of the checkbox to true.

  2. If the cell contains the text "no", the toggle element should have a class of .on and set the checked attribute of the checkbox to false.

Below is the code I have written so far:

// TRIM FUNCTION
if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    }
}

// TOGGLE FUNCTIONALITY
$(document).ready(function() {

    // FIND DEV YES/NO INPUT & CHECK VALUE
    var ynCell = $("td.yn");
    $(ynCell).each(function() {
        var ynValue = $(ynCell).text().toLowerCase().trim();
        // IF VALUE = NO, DISPLAY TOGGLE CLASS 'ON'
        // IF VALUE = YES, DISPLAY TOGGLE CLASS 'OFF'
        if (ynValue.indexOf('no') != -1) {
            $(".switch").parent().find('input:checkbox').attr('checked', false);
            $(".switch").removeClass('off').addClass('on');
        } else if (ynValue.indexOf('yes') != -1) {
            $(".switch").parent().find('input:checkbox').attr('checked', true);
            $(".switch").removeClass('on').addClass('off');
        }
    });

    $(".switch").each(function() {
        if ($(this).parent().find('input:checkbox').length) {
            if (!$(this).parent().find('input:checkbox').hasClass("show")) {
                $(this).parent().find('input:checkbox').hide();
            }
            if ($(this).parent().find('input:checkbox').is(':checked')) {
                $(this).removeClass('on').addClass('off');
            } else {
                $(this).removeClass('off').addClass('on');
            }
        }
    });

    $(".switch").click(function() {
        if ($(this).hasClass('on')) {
            $(this).parent().find('input:checkbox').attr('checked', true);
            $(this).removeClass('on').addClass('off');
        } else {
            $(this).parent().find('input:checkbox').attr('checked', false);
            $(this).removeClass('off').addClass('on');
        }
    });

});
th {
  text-align: left;
}

.switch-container {
  padding: 5px;
}
.switch {
    position: relative;
    display: inline-block;
    font-size: 1.6em;
    font-weight: bold;
    color: #ccc;
    height: 18px;
    padding: 6px 6px 5px 6px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background: #ececec;
    cursor: pointer;
    font-size: 14px;
}
body.IE7 .switch {
    width: 78px;
}
.switch span {
    display: inline-block;
    width: 35px;
}
.switch span.on {
    color: #5cbacc;
    margin-left: 5px;
}
.switch span.off {
    margin-left: 10px;
}
.switch .toggle {
    position: absolute;
    top: 1px;
    width: 40px;
    height: 25px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background: #fff;
    z-index: 999;
    -webkit-transition: all 0.15s ease-in-out;
    -moz-transition: all 0.15s ease-in-out;
    -o-transition: all 0.15s ease-in-out;
    -ms-transition: all 0.15s ease-in-out;
}
.switch.on .toggle {
    left: 1%;
}
.switch.off .toggle {
    left: 56%;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<table style="width:100%">
  <tr>
    <th>Yes/No</th>
    <th>Toggle</th> 
  </tr>
  <tr>
    <td class="yn">Yes</td>
    <td class="switch-container">
      <input type="checkbox" checked>
      <div class="switch"><div class="toggle"></div>
      <span class="on">YES</span><span class="off">NO</span></div></td>
  </tr>
  <tr>
    <td class="yn">No</td>
    <td class="switch-container">
      <input type="checkbox" checked>
      <div class="switch"><div class="toggle"></div>
      <span class="on">YES</span><span class="off">NO</span></div></td>
  </tr>
</table>
  <script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
</body>
</html>

Any recommendations on enhancing my script and resolving any issues are appreciated.

Here is a link to a JS Bin for testing: https://jsbin.com/derevarixo/edit?html,css,js,output

Answer №1

When using the .each() loop, make sure to utilize this to access the current loop element instead of $(ynCell), which encompasses all the yes/no cells. To locate the corresponding .switch element, employ .find() within the current row.

// TRIM FUNCTION
if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    }
}

// TOGGLE FUNCTIONALITY
$(document).ready(function() {

    // FIND DEV YES/NO INPUT & CHECK VALUE
    var ynCell = $("td.yn");
    $(ynCell).each(function() {
        var ynValue = $(this).text().toLowerCase().trim();
        var row = $(this).closest("tr");
        // IF VALUE = NO, DISPLAY TOGGLE CLASS 'ON'
        // IF VALUE = YES, DISPLAY TOGGLE CLASS 'OFF'
        if (ynValue.indexOf('no') != -1) {
            row.find('input:checkbox').attr('checked', false);
            row.find(".switch").removeClass('off').addClass('on');
        } else if (ynValue.indexOf('yes') != -1) {
            row.find('input:checkbox').attr('checked', true);
            row.find(".switch").removeClass('on').addClass('off');
        }
    });

    $(".switch").each(function() {
        if ($(this).parent().find('input:checkbox').length) {
            if (!$(this).parent().find('input:checkbox').hasClass("show")) {
                $(this).parent().find('input:checkbox').hide();
            }
            if ($(this).parent().find('input:checkbox').is(':checked')) {
                $(this).removeClass('on').addClass('off');
            } else {
                $(this).removeClass('off').addClass('on');
            }
        }
    });

    $(".switch").click(function() {
        if ($(this).hasClass('on')) {
            $(this).parent().find('input:checkbox').attr('checked', true);
            $(this).removeClass('on').addClass('off');
        } else {
            $(this).parent().find('input:checkbox').attr('checked', false);
            $(this).removeClass('off').addClass('on');
        }
    });

});
th {
  text-align: left;
}

.switch-container {
  padding: 5px;
}
.switch {
    position: relative;
    display: inline-block;
    font-size: 1.6em;
    font-weight: bold;
    color: #ccc;
    height: 18px;
    padding: 6px 6px 5px 6px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background: #ececec;
    cursor: pointer;
    font-size: 14px;
}
body.IE7 .switch {
    width: 78px;
}
.switch span {
    display: inline-block;
    width: 35px;
}
.switch span.on {
    color: #5cbacc;
    margin-left: 5px;
}
.switch span.off {
    margin-left: 10px;
}
.switch .toggle {
    position: absolute;
    top: 1px;
    width: 40px;
    height: 25px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background: #fff;
    z-index: 999;
    -webkit-transition: all 0.15s ease-in-out;
    -moz-transition: all 0.15s ease-in-out;
    -o-transition: all 0.15s ease-in-out;
    -ms-transition: all 0.15s ease-in-out;
}
.switch.on .toggle {
    left: 1%;
}
.switch.off .toggle {
    left: 56%;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<table style="width:100%">
  <tr>
    <th>Yes/No</th>
    <th>Toggle</th>
  </tr>
  <tr>
    <td class="yn">Yes</td>
    <td class="switch-container">
      <input type="checkbox" checked>
      <div class="switch"><div class="toggle"></div>
      <span class="on">YES</span><span class="off">NO</span></div></td>
  </tr>
  <tr>
    <td class="yn">No</td>
    <td class="switch-container">
      <input type="checkbox" checked>
      <div class="switch"><div class="toggle"></div>
      <span class="on">YES</span><span class="off">NO</span></div></td>
  </tr>
</table>
  <script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
</body>
</html>

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

How can HTML and CSS be linked to display images independently?

Check out this code: body{ background-image:url('http://wallpoper.com/images/00/31/33/51/black-background_00313351.jpg'); } div.header{ background-color:#F0F8FF; text-align:center; padding:3px; ...

Click on the logo to return to the home page

Logo Link Causing Menu Alignment Issue After setting the logo as a link, the menu unexpectedly shifts to the right. Upon inspecting the menu element, it appears that there is an additional hidden menu link on the left side leading to index.html. Can anyon ...

Utilizing the Sheet Elite API - Step-by-Step Guide for Sending Data to a Designated Sheet Through a POST Request

Recently, I've been working on a project that involves using the Sheet Best API to submit data directly to Google Sheets. However, I'm running into an issue where the data is only being sent to the first sheet out of three. Despite having all the ...

Div overlaps div on certain screen dimensions

When the screen size falls within a specific range, typically in the low 1000s, there is an issue where my content div overlaps completely with the navigation div. It appears as if both divs are positioned at the top of the page. Below is the HTML code sn ...

The CSS overflow property is a great tool to demonstrate how a box can be neatly cut off at its

According to the specifications outlined in this resource, In situations where overflow occurs, the 'overflow' property determines if a box is clipped to its padding edge. Additionally, it specifies whether or not a scrolling mechanism will b ...

GraphQL queries that are strongly-typed

Currently working on a Vue CLI project where I am utilizing axios as my request library. In all the examples I've come across, they use strings for queries like this: { hero { name friends { name } } } Given that I am employing ...

Why does the page reload before reaching the server-side processing page? Any thoughts on what might be causing this?

Utilizing a JSON object and multiple ajax calls to a webmethod for data insertion into the database, we encountered an issue where the page reloads before processing the data. This results in errors indicating that certain parameters are required but not s ...

Is relying on getState in Redux considered clunky or ineffective?

Imagine a scenario where the global store contains numerous entities. Oranges Markets Sodas If you want to create a function called getOrangeSodaPrice, there are multiple ways to achieve this: Using parameters function getOrangeSodaPrice(oranges, s ...

Using Node.js, securely encode data using a private key into a base64 format that can only be decoded on the server side

Here is my specific situation: An http request arrives at the server for a login action A user token needs to be created. This token consists of a Json object composed of different fields. It is then converted to a string and encoded in Base64. const ...

I created a new game where I can select two images to display, but for some reason, it is only showing one

My rock paper scissors game functions well, except for one issue. I programmed it to display both the player's choice and the bot's choice along with an outcome message (win, tie, or lose). However, I encountered a problem where only the player&a ...

What steps should I take to execute a npm demonstration?

Here, you can find a great example of how to convert a full JSON file into a CSV format. To make it work, I downloaded the json-2-csv program by running the command npm install json-2-csv After setting up my JavaScript file with the example code, I encou ...

Continue to alter elements by stacking them on top of each other

Currently, I am in the process of familiarizing myself with CSS3 3D transforms. However, I am encountering difficulties in keeping elements that are undergoing transformation on top of other elements. If you'd like to take a look at what I have accom ...

Can anyone suggest an effective method for displaying images using JavaScript by specifying a route and filename?

Currently, I have the following code snippet: const route = '/Images/Banner/'; const slides = [ { name: "banner-01", url: `${route}banner-01.png` }, { name: "banner-02", url: `${route}banner-02.pn ...

Ways to modify the data within a column for every row in a table without relying on props in Vue.js (specifically Element-ui)

I've been stuck on this issue for quite some time now. I've created a table with 3 columns, and for the first two columns, I can easily display the contents of each row using the prop property. However, for the third column, I need to display inf ...

Attempting to Send an Ajax Request and Utilize the Result within a React Component

I am having issues with my tweet box component. I have a submit function that triggers the getAllTweets function when called. The problem is that I am unable to capture the value of the field and pass it on to the getAllTweets function in order to create ...

Calculating the sum of numbers within a PHP Foreach loop

I'm looking to calculate the total sum of individual records within a foreach loop. My table structure is as follows: <table> <tr> <th>Person Name</th> <th>Balances</th> <th>Total</th> & ...

Using JavaScript, transform a client's date/time string into a JSON-compatible date/time string

I need to find a way to convert a client's date/time string on a form into a JSON date/time string using JavaScript with moment.js for a Django REST API backend service. Here is the initial attempt: document.getElementById("dt_tm").value = moment(do ...

Iterating over selected checkboxes and setting custom styles in SCSS

As a beginner in SCSS, I am uncertain if it is possible to create a loop function that would compile the following code: I aim to apply certain CSS properties to specific elements when a particular input button is checked. My goal is to achieve this using ...

Issue with Favicon display in all versions of Internet Explorer

Visit my website. I have attempted multiple solutions found on Stack Overflow and different forums, yet I am unable to make it work. The code runs perfectly in all browsers except for Internet Explorer (regardless of the version) :( Can anyone provide ass ...

Styling for a solo section

As a novice, I am seeking guidance on how to apply the following CSS as an inline style for just one div. The issue arises when I attach it as regular CSS and it affects all the div elements on the page. Here is the code: @keyframes blink { 0% { ...