Troubleshooting issue with changing class based on input values

It appears that there is an issue with the functionality when switching values on page load.

Initially, I was able to make it work for a single switch, but now that there are multiple switches on the page, toggling affects all of them. How can I modify it to work independently for each one?

$('.switch .inactive').hide();

var switchStatus = $('.switch').next('input').val();

// 1 = disable
// 0 = enabled
if (switchStatus == '1') {
  $('.switch .active').hide();
} else {
  $('.switch .active').show();
}

$('.switch').click(function() {
  $('.inactive, .active').toggle();

  var featureStatus = $(this).find('#ProductFeatures_TP_Status').val();
  //console.log(featureStatus);
  if (featureStatus == "1") {
    $(this).find('#ProductFeatures_TP_Status').val('0');
  } else {
    $(this).find('#ProductFeatures_TP_Status').val('1');
  }

});
.panel-heading {
  cursor: pointer;
  margin: 0;
}
.panel-heading .status {
  float: right;
}
.panel-collapse {
  display: none;
}
.panel-collapse.open {
  display: block;
}
.panel-body .col-md-6.left {
  padding-left: 0;
}
.panel-body .col-md-6.right {
  padding-right: 0;
}
.panel-body .redactor-editor {
  min-height: 100px !important;
}
.switch {
  float: left;
  font-size: 1.5em;
  margin: -4px 10px 0 -5px;
}
.switch .active {
  color: green;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<div class="switch ProductFeatures_TP_Status">
  <i class="fa fa-toggle-on active"></i>
  <i class="fa fa-toggle-on fa-rotate-180 inactive"></i>
  <input type="hidden" id="ProductFeatures_TP_Status" name="ProductFeatures_TP_Status" value="0">
</div>

<div class="switch ProductFeatures_TP_Status">
  <i class="fa fa-toggle-on active"></i>
  <i class="fa fa-toggle-on fa-rotate-180 inactive"></i>
  <input type="hidden" id="ProductFeatures_TP_Status1" name="ProductFeatures_TP_Status1" value="1">
</div>

<div class="switch ProductFeatures_TP_Status">
  <i class="fa fa-toggle-on active"></i>
  <i class="fa fa-toggle-on fa-rotate-180 inactive"></i>
  <input type="hidden" id="ProductFeatures_TP_Status2" name="ProductFeatures_TP_Status2" value="1">
</div>

Answer №1

Is this what you're looking for? http://jsfiddle.net/gb13r1b3/

I simply located the classes '.inactive, .active' in relation to the clicked .switch

$('.switch').click(function() {
  $(this).find('.inactive, .active').toggle();

  var featureStatus = $(this).find('[id^=ProductFeatures_TP_Status]').val();
    console.log(featureStatus);
  //console.log(featureStatus);
  if (featureStatus == "1") {
    $(this).find('[id^=ProductFeatures_TP_Status]').val('0');
  } else {
    $(this).find('[id^=ProductFeatures_TP_Status]').val('1');
  }

UPDATE: the syntax [id^=ProductFeatures_TP_Status] locates any id that begins with ProductFeatures_TP_Status. Upon clicking the .switch, there is only one id that starts with ProductFeatures...

UPDATE-2: http://jsfiddle.net/gb13r1b3/1/

UPDATE-3: http://jsfiddle.net/gb13r1b3/5/

Answer №2

Based on the initial sentence in your inquiry, it seems you are open to exploring different solutions. Here is a refined CSS approach that could work for you, albeit with some modifications to your HTML structure.

To implement this method, you will need to convert all your input elements into checkboxes and position labels directly after them in your HTML. These labels should include the desired FontAwesome icons.

Subsequently, using CSS, you can hide the checkboxes off-screen and alter the styling of the icons within the adjacent labels based on the checked status of each respective input element.

*{box-sizing:border-box;color:#000;font-family:arial;margin:0;padding:0;}
input{
  left:-9999px;
  position:absolute;
}
label{
  height:24px;
  display:inline-block;
  margin:5px;
  overflow:hidden;
  width:27px;
  white-space:nowrap;
}
label>i::before{
  display:inline-block;
  font-size:24px;
  transform:rotate(180deg);
}
input:checked+label>i::before{
  color:#090;
  transform:rotate(0deg);
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet">
<input id="ProductFeatures_TP_Status" type="checkbox" value="1">
<label for="ProductFeatures_TP_Status"><i class="fa fa-toggle-on"></i>Label 1</label>
<input checked id="ProductFeatures_TP_Status1" type="checkbox" value="1">
<label for="ProductFeatures_TP_Status1"><i class="fa fa-toggle-on"></i>Label 2</label>
<input checked id="ProductFeatures_TP_Status2" type="checkbox" value="1">
<label for="ProductFeatures_TP_Status2"><i class="fa fa-toggle-on"></i>Label 3</label>

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

Send an API call for every item in a given list

There is a function that I am working with: updateCustomers = (input) => { //let urls = input; let urls = [{ name: "localhost:8081", url: "http://localhost:8081" }, { name: "localhost:8082", url: "http://localhost:8081" }, { ...

Having trouble with my $.ajax() call function, it's not behaving how I expected

When I send an ajax request like this: $.ajax({ type: "POST", url: "/videos", data: { title: oembed.title } }); within the function call to the Embedly API: $('a.oembed').embedly({maxWidth:300,'method':'replace'}). ...

The operation of executing `mongodb - find()` does not exist as a function

I am having trouble printing all documents from the "members" collection. I attempted to use the find() function, but encountered an error stating that find() is not a function. Here is a snippet from member_model.js located in the models/admin folder: v ...

Ensure page is updated after an AJAX request in jQuery Mobile by refreshing the page

My jQueryMobile page structure in index.html looks like this: <div data-role="page"> <div data-role="header">...</div> <div data-role="content">...</div> <div data-role="footer">...</div> </div& ...

How can I fetch a value from a database and set it as the selected option in a

I am facing an issue with the usage of the selectpicker plugin from Bootstrap in order to select multiple items. My requirement is to create a modal for editing where the data is fetched from previous records, particularly an array. I am looking for a way ...

Exploring the jQuery DOM: Understanding the .prev() traversal method

I am attempting to retrieve an input value using jQuery. In my actual code, I have multiple inputs and buttons, so using code like: .middle() won't do the trick! I need to navigate from the button and upwards. HTML <p>Help</p> <input ...

What is the process for opening and populating dialogs from dynamically mapped cards?

I have a unique array of JSON data that is connected to Material-UI (MUI) cards. Each card features a button that triggers a dialog to open. When clicking the button on a card, I aim to pass the specific value of GroupName into the dialog. In my case, ther ...

Is there a way to exit from await Promise.all once any promise has been fulfilled in Chrome version 80?

Seeking the most efficient way to determine which server will respond to a request, I initially attempted sending requests in sequence. However, desiring to expedite this probing process, I revised my code as follows: async function probing(servers) { ...

Ways to pass JavaScript variables to a Python script

Hey there! I'm currently facing an issue with retrieving variables from JS to use in my python code. Despite trying methods like AJAX and JQuery, I haven't had much success yet. It's possible that I'm missing something crucial in the pr ...

How does Backbone.js tackle error handling when receiving messages from Rails?

Can anyone using backbone.js lend a hand? How can error messages from a rails app be encoded when integrating with backbone.js? For instance, how should flash messages like "record not found" be handled? While errors are usually defined on the client sid ...

Struggling to Parse JSON Arrays in Node.js

Embarking on a journey with Node JS and Express, I find myself facing the challenge of developing a small proof of concept API in Node. The main hurdle I'm currently encountering stems from my limited understanding of how to parse JSON arrays to extr ...

Utilizing JavaScript to retrieve input names from arrays

This is the HTML form that I am currently working with: <form action="#" method="post"> <table> <tr> <td><label>Product:<label> <input type="text" /></td> <td><label>Price:<label> ...

Unable to retrieve information from the JSON object

Here's the script I'm working with: <script type="text/javascript> function getData(username){ $.ajax({ url: '{% url "data" %}', data: { ' ...

Tips for utilizing jQuery to substitute strings within a content variable?

$content = "Please locate the student results where Date of birth **IS BETWEEN** 2012-02-18 00:00:00 AND 2013-02-18 00:00:00 AND name **IS NOT EQUAL TO** 'John' AND marks **IS BETWEEN** 40 AND 75 AND grade **EQUAL TO** 'A' AND AGE **I ...

Guide on setting up create-next-app with version 12 instead of the latest version 13

For an upcoming Udemy course, I am required to develop a Next.js project. However, it specifically needs to be built using Next.js version 12 rather than the latest version 13. Does anyone know how I can achieve this? ...

style of placing a space between objects

Is there a way to create space between the border (underline hover effect) and have the color of the line be red? a { text-decoration: none } li { display: inline; } li:hover { text-decoration: underline; } <li><a href=""> abc < ...

Exploring the concept of 'mapping' in jQuery: A guide to traversing an array with varying variable values

I need assistance in linking two unrelated data points together. I have an array that stores images at specific positions, and a variable that can hold different values (1, 2, or 3). My goal is to connect the array position (1, 2, or 3) with the variable v ...

Ways to create a border button with a matching width to the text above using CSS

Is it possible to style a border button in CSS so that the width matches the text above? I am trying to achieve a clean look for the navigation selected text, where the border-bottom aligns with the text above. Here is an example of what I have attempted ...

What is the process for submitting a post request with custom fields to the Wordpress rest api?

Currently, I am attempting to make a post request to /wp-json/wp/v2/posts while also including custom fields. However, it seems that although the request field is successfully being sent, the custom fields are not updating with the data I am trying to send ...

Updating the Scale of the Cursor Circle on my Portfolio Site

I attempted to find tutorials on creating a unique circle cursor that can hide the regular mouse cursor as well. After implementing it with a difference blend mode, I encountered an issue where I wanted the scale to change when hovering over a link. The ...