Switch the background color of the checkbox div or label with a single click

I have successfully implemented the following code, with one small issue. When I select the checkbox, the background color of the div changes from #fff to #ffe600 as expected. However, after submitting the form and refreshing the page, the background color reverts back to #fff. Is there a way to ensure that the background color remains #ffe600 even after the page is refreshed post form submission? While the checkbox stays checked after the page refresh, the div background color resets to #fff. Any insights on how to maintain the div background color as #ffe600 upon page refresh would be greatly appreciated. This issue has left me puzzled.

function myFunction(x, _this) {
  if (_this.checked) {
    x.style.backgroundColor = '#ffe600';
  } else  {
    x.style.backgroundColor = '#fff';
  }
}
#product1 {
  background-color: #fff;
  padding: 3px 5px 3px 7px;
  margin-top: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product1">
  <label class="chk">
    <input type="checkbox" onChange="myFunction(product1, this)" name="select_product" value="Y" />Label goes here.</label>
</div>

Thanks!

Answer №1

To highlight the currently checked boxes, you can use jQuery to check on load and apply the desired styling.

$('input[type=checkbox]').each(function(){
  if($(this).is(':checked'))
$(this).parent().parent().css('backgroundColor','#ffe600');
  else
$(this).parent().parent().css('backgroundColor','#fff');
});
function updateColor(x, _this) {
  if (_this.checked) {
    x.style.backgroundColor = '#ffe600';
  } else  {
    x.style.backgroundColor = '#fff';
  }
}
#product1 {
  background-color: #fff;
  padding: 3px 5px 3px 7px;
  margin-top: 6px;
}
#product2 {
  background-color: #fff;
  padding: 3px 5px 3px 7px;
  margin-top: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product1">
  <label class="chk">
    <input type="checkbox" onChange="updateColor(product1, this)" name="select_product" value="Y" />Label goes here.</label>
</div>
<div id="product2">
<label class="chk">
<input checked type="checkbox" onChange="updateColor(product2, this)" name="select_product2" value="V" />Label goes here 2.</label>
</div>

Answer №2

Do you really need to refresh the page every time? It seems like AJAX is already being used.

Have you implemented a function to handle form submission? If so, you can prevent the page from refreshing by following these steps:

<form onsubmit="submitHandler(event)">
      // form elements
</form>

Here's a JavaScript example of how to achieve this:

function submitHandler(event) {
    event.preventDefault();
    // process form data
}

By using event.preventDefault(), you can prevent the page from reloading and maintain the background color of your element.

Answer №3

To save and retrieve the checkbox state, you can utilize either localstorage or Cookie. Upon page load, you can access the stored state from these methods. Alternatively, you can implement a check similar to myFunction when the page loads, like so:

window.onload = function(){
 var checkBoxElement = document.querySelector("div#product1 input[type='checkbox']");

 var productElement = document.getElementById("product1"); 
 if (checkBoxElement.checked) {
    productElement.style.backgroundColor = '#ffe600';
  } else  {
    productElement.style.backgroundColor = '#fff';  
}

Answer №4

Creating a function with jQuery to handle checkbox validation and formatting upon document load and when the checkbox is clicked.

<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    var changeColor = function(){
        if($("#select_product").is(":checked")) $("#product1").css("background-color", "#ffe600");
        else $("#product1").css("background-color", "#fff");
    }
    $(document).ready(function(){
        changeColor();
        $("#select_product").click(changeColor);
    });
</script>
<div id="product1">
    <label class="chk">
    <input type="checkbox" id="select_product" value="Y">Label text.</label>
</div>
</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

One way to automatically create unique reference numbers is to generate a random number between 1 and 99 and append it to a date format, such as YYMMDD. For example,

I have a code that generates numbers like 030317-001 to 030317-010 in a list. How can I modify it so that the same sequence is generated with just one button click, without any repeats, up to a maximum of say 030317-099? <?php $x = date("dmy");// ...

Form for sending mail using custom AJAX capabilities

Here is the HTML form code I have: <form id="main-contact-form" name="contact-form"> <div class="row wow fadeInUp" data-wow-duration="1000ms" data-wow-delay="300ms"> <div class="col-sm-6"> ...

Switching the navbar state from a regular mode to a collapsed mode can be done manually

I need help with my navbar design: <nav class="navbar fixed-top navbar-expand-sm navbar-light"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle=&q ...

Is it possible to provide unrestricted support for an infinite number of parameters in the typing of the extend function from Lodash

I am utilizing the "extend" function from lodash to combine the objects in the arguments as follows: import { extend } from 'lodash'; const foo1 = { item: 1 }; const foo2 = { item: 1 }; const foo3 = { item: 1 }; const foo4 = { item: 1 }; const f ...

The correct value is not being received by the AJAX POST

I am facing an issue where the $_POST variable in PHP is getting assigned 'undefined' when I try to post the value of a selected radio button. How can I make sure that the correct value is assigned to the $_POST variable? I have tried using URIen ...

ways to retrieve script template variable in angularjs application

I have written scripts to create a whiteboard using canvas inside the template page of AngularJS. Now I need to assign the values of the points[] variable to an AngularJS scope variable. <script> var points = []; </script> How can I access th ...

Overlapping Dropdown Javascript Menus

To achieve the desired effect in the header, I need to create two expandable dropdown menus for the first two titles. My coding experience is limited, especially when it comes to javascript and jquery. Currently, I have managed to create the effect for one ...

How can I effectively combine jquery validate with $.ajax for validation and form submissions?

How can I effectively use jquery validate and $.ajax in conjunction? My goal is to save form data using Ajax after it has been successfully validated: jQuery(document).ready(function() { $('#np-submit').click(function() { if($("#new ...

The HTML form submission button fails to submit the form and instead just refreshes the page

I'm struggling to get the save button working on my Chrome Extension settings page. The .click() event doesn't seem to be activating at all. I've included my code below. Should I use the commented out button instead (see below)? HTML <! ...

Steps for incorporating code to calculate the total price and append it to the orderMessage

I am seeking help with this program that my professor assigned to me. The instructions marked by "//" are the ones I need to implement in the code, but I'm struggling to understand how to proceed. Any assistance would be greatly appreciated, even just ...

"Implementing a feature to dynamically load Blogspot post content using JSON upon user

$.ajax({ url: 'https://uniquewebsite.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script', type: 'get', dataType: "jsonp", success: function(data) { var entry = data.feed.entry; ...

An error in AngularJS occurred, stating: "TypeError: Attempted to access an undefined property 'apply'"

Having issues with my angularjs app that includes a form with a dropdown list and a datetimepicker. Whenever I change the dropdown list selection, I want the date displayed in the datetimepicker to be updated accordingly. After changing the selected item ...

JavaScript: set values to elements in an array

Below is the code snippet I am working with: function gotData(data){ result = data.val() const urls_kws = Object.keys(result) .filter(key => result[key].last_res > 10) var keywords = urls_kws; c ...

Encountering an error while attempting to launch an AngularJS application on Node.js? Let's

Currently, I am in the process of learning Angular. Whenever I attempt to run my code, an error message pops up: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a737a7c6b6d70715f2b312f3115">[email protected]< ...

Issue with code failing to insert object into an array

I've been struggling to add a group of objects from a JSON file into an array. Despite trying to use the push method, the length of the array remains at 0. I'm puzzled by what could be going wrong. The JSON data is being parsed correctly as I&apo ...

HTML form for selecting shipping method in PayPal

In my shopping cart setup, I offer two shipping methods: 'express' and 'standard'. I'm wondering if it's feasible to transmit this data to PayPal using HTML variables? ...

AMD module cannot be required within a registerSuite function in Intern.js

I have encountered a situation where I am trying to include some code using the require function: define(function(require) { return stuff { my_func: function() { return 1; } }; }); When I attempt to require thi ...

The stacking order of React components

I am having an issue with the Z-index in my component-based React app. I currently have a list component that contains items, and I want to adjust the CSS scale and z-index to display one item in front of the others. The problem arises when the hovered it ...

Is there a way to consistently apply default props to a styled component?

Currently, I am working with React, Material UI, and Styled Components. My goal is to create a personalized Input field where the size='small' is always passed as a prop to my component. To clarify, if the user neglects to include the size attri ...

Encountering a build time issue while incorporating Redis into Next.js

Incorporating Redis into my Next.js project has been beneficial overall. However, during the build process (next build), an error arises when it attempts to connect to Redis, resulting in the following message: Collecting page data ..[ioredis] Unhandled e ...