The onchange function in JavaScript is malfunctioning

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Product page</title>
    <!-- Fonts -->
    <style>
      /* Custom Styling */
        html, body {
          height: 100%;
          width: 100%;
          margin: 0;
          font-family: 'Roboto', sans-serif;
        }

        .container {
          max-width: 1200px;
          margin: 0 auto;
          padding: 15px;
          display: flex;
        }

        /* Columns */
        .left-column {
          width: 65%;
          position: relative;
        }

        .right-column {
          width: 35%;
          margin-top: 60px;
        }


        /* Left Column */
        .left-column img {
          width: 100%;
          position: absolute;
          left: 0;
          top: 0;
          opacity: 0;
          transition: all 0.3s ease;
        }

        .left-column img.active {
          opacity: 1;
        }


        /* Right Column */

        /* Product Description */
        .product-description {
          border-bottom: 1px solid #E1E8EE;
          margin-bottom: 20px;
        }
        .product-description span {
          font-size: 12px;
          color: #358ED7;
          letter-spacing: 1px;
          text-transform: uppercase;
          text-decoration: none;
        }
        .product-description h1 {
          font-weight: 300;
          font-size: 52px;
          color: #43484D;
          letter-spacing: -2px;
        }
        .product-description p {
          font-size: 16px;
          font-weight: 300;
          color: #86939E;
          line-height: 24px;
        }

        /* Product Configuration */
        .product-color span,
        .cable-config span {
          font-size: 14px;
          font-weight: 400;
          color: #86939E;
          margin-bottom: 20px;
          display: inline-block;
        }
        /* Cable Configuration */
        .cable-choose {
          margin-bottom: 20px;
        }

        .cable-choose button {
          border: 2px solid #E1E8EE;
          border-radius: 6px;
          padding: 13px 20px;
          font-size: 14px;
          color: #5E6977;
          background-color: #fff;
          cursor: pointer;
          transition: all .5s;
        }

        .cable-choose button:hover,
        .cable-choose button:active,
        .cable-choose button:focus {
          border: 2px solid #86939E;
          outline: none;
        }

        .cable-config {
          border-bottom: 1px solid #E1E8EE;
          margin-bottom: 20px;
        }

        <!-- Product Pricing --!>
        
      
        @media (max-width: 940px) {
          .container {
            flex-direction: column;
            margin-top: 60px;
          }

          .left-column,
          .right-column {
            width: 100%;
          }

          .left-column img {
            width: 300px;
            right: 0;
            top: -65px;
            left: initial;
          }
        }

        @media (max-width: 535px) {
          .left-column img {
            width: 220px;
            top: -85px;
          }
        }
    </style>
    <!-- CSS -->
    <link href="style.css" rel="stylesheet">
    <meta name="robots" content="noindex,follow" />

  </head>

  <body>
    <main class="container">

      <!-- Left Column / Headphones Image -->
      {%  for p in products  %}
      <div class="left-column">
        <img data-image="red" class="active" src="{{p.image.url}}" alt="">
      </div>
      


      <!-- Right Column -->
      <div class="right-column">

        <!-- Product Description -->
        <div class="product-description">
          <span>{{p.vendor}}</span>
          <h1>{{p.title}}</h1>
          <p>{{p.description}}</p>
        </div>
        {%  endfor  %}

        <!-- Product Configuration -->
        

      
        <!-- </div> -->
        

        <!-- Product Pricing -->
         
          
      </div>
      
    </main>
    
           <!-- Related Products Section -->
           <div class="related-products">
            <div style="text-align: center;">
                <h2>Related Products</h2>
            </div>
    
            
            {% endfor %}

    <!-- Scripts -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" charset="utf-8"></script>
    {%  for i in colors  %}
    <script>

      function colorID(){
        window.location.href =window.location.pathname + `?color=${{i.id}}`
      }

    </script>
    {%  endfor  %}
  </body>
</html>

There is an issue with the script where the color ID is not being assigned unique values correctly to each checkbox.

http://127.0.0.1:8000/product/prdcadfacebaa/?color=$4

The script seems to always assign the value of 4 to the color parameter regardless of which checkbox is selected. This inconsistency can be observed in the provided images.

Answer №1

As I review your code, it seems that you are looping over an array of colors and creating a script block in each iteration with the same function. This approach may lead to issues. It is recommended to remove the for loop so that you have one script block with the colorID function.

The next issue I noticed is regarding how you are calling the colorID function:

<input type="checkbox" onchange="colorID('{{c.id}}')" id="checkbox1" style="display: none;">

You are passing a parameter to the function, but the colorID function does not currently accept any parameters. To make this work correctly, you should modify the function definition to include a parameter like this:

function colorID(cID){
        window.location.href = window.location.pathname + '?color=' + cID;
      }

Additionally, you were using backticks (`) in your script, which I replaced with single quotes ('). While I am not a JavaScript expert, using backticks in this context did not seem appropriate to me. These suggestions are based on fundamental coding principles.

Answer №2

After some investigation, I found a solution by making minor changes to the code. Instead of

{%  for c in colors  %}

            <div class="color-choose">
              <input type="checkbox" onchange="colorID('{{c.id}}')" id="checkbox1" style="display: none;">
              <label for="checkbox1"value="✔" style="display: inline-block; width: 40px; height: 40px; background-color: {{c.code}}; border-radius: 50%;border: 2px solid #FFFFFF; cursor: pointer;float: left; margin-right: 10px;box-shadow: 0 1px 3px 0 rgba(0,0,0,0.33);"></label>
            </div>
            {%  endfor  %}

I updated the code to

<a href="?colorID={{c.code}}" style="display: inline-block; width: 40px; height: 40px; background-color: {{c.code}}; border-radius: 50%; border: 2px solid #FFFFFF; cursor: pointer; float: left; margin-right: 10px; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.33);">

Additionally, I removed the script from the code.

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

Is the state mutated when using the .map() function to update it?

I am new to working with React and I am still struggling to understand state mutation. After reading multiple posts on this topic, I am finding it difficult to grasp the concept of state mutation. So, I have decided to seek clarification on this matter. ...

In what situations should the `#` symbol be used to select a DOM element?

There are times when I have to retrieve elements in the following ways: var object = document.getElementById('ObjectName'); Other times, it's done like this: var object = document.getElementById('#ObjectName'); What distinguishes ...

A guide on transforming Jonatas Walker's TimePicker into a custom JavaScript class or a versatile jQuery plugin

I came across a timepicker solution on this Stack Overflow answer that I really liked. However, I encountered difficulties trying to implement it in a project where input elements are dynamically created. It seemed like the timepicker required specific han ...

Dynamically setting the default selection in a dropdown menu

When choosing a default value from a dynamically populated dropdown using JSON data, I attempted to use regCtrl.screeningTypeList[0] without success. <select ng-init="regCtrl.user.screeningType.screeningTypeId=regCtrl.screeningTypeList[0]" ng-model="re ...

Conceal the calendar icon from the date-type HTML input field specifically on the Firefox

The situation at hand is quite straightforward. <input type="date /> When viewed on Firefox (both desktop and mobile), it appears as follows: https://i.stack.imgur.com/S2i0s.png While the internet provides a solution specifically for Chrome: ...

The ng-disabled directive in AngularJS fails to disable the button as expected

I'm having an issue with setting an input button to disabled when a user selects a specific value from a select box: Here is my select menu: <select id="jobstatus" name="jobstatus" ng-model="associate.JobStatus" class="form-control"> & ...

jQuery failing to trigger onClick event for a specific group of buttons

Javascript: <script> $(document).ready(function(){//Implementing AJAX functionality $(".acceptorbutton").on('click', function(){ var whichClicked = this.attr('name'); ...

Is it possible to resend an AJAX request using a hyperlink?

Is it possible to refresh only the AJAX request and update the content fetched from an external site in the code provided below? $(document).ready(function () { var mySearch = $('input#id_search').quicksearch('#content table', ...

Tips for including HTML tags in strings without causing issues with nested tags

I am struggling with a string that contains both text and HTML tags, specifically <a href=""></a> tags. My goal is to apply the "i" tag around the text outside of the "a" tags without creating nested tags like: <i><a href=""></a ...

Is it possible to dynamically insert one module into another module?

Let's say I have 2 modules in two separate files: The first one is for everyone, let's call it myApp: var myApp = angular.module('myApp', ['dependency.one', 'dependency.one']); In another file named admin.js, I ha ...

Adjust THREE.PerspectiveCamera's distance without altering its viewing orientation

I have a PerspectiveCamera in THREE.js positioned somewhere in space as a child of a mesh. The camera is currently looking at the mesh with local coordinates [0, 0, 0]. I am looking for a way to change the distance of the camera from the mesh without chang ...

Determine the total number of instances an HTML div element is utilized within a PHP script

Having conducted interviews with over 40 individuals, I'm looking to showcase this with a PHP script. Each interview comes with its own set of CSS classes, and adding an extra class or utilizing an existing one can help me determine the total number ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

Issue with Angular: Unable to update model before modal closure on submit

I have a search form that is displayed within a modal window created using Angular UI Bootstrap. The input fields in the form update the ng-model when submitted. <script type="text/ng-template" id="mobileSearchPanel"> <form> ...

What are the best practices for using .toString() safely?

Is it necessary for the value to return toString() in order to call value.toString()? How can you determine when you are able to call value.toString()? <script> var customList = function(val, lst) { return { value: val, tail: lst, t ...

Bootstrap carousel button that tracks the number of clicks

Unfortunately, I am facing a challenging issue with creating a click counter for the Bootstrap carousel button. The problem seems to be related to the span element for the previous and next icons. The button counter is not registering clicks on the respec ...

Application of id missing on all buttons in Bootstrap tour template

I'm having an issue with applying a new id to the next button in a Bootstrap tour template. I added the id to the button, but it only seems to work for the first stage and not the subsequent ones. Can anyone provide insight into why this might be happ ...

Issue: Query is not re-executing after navigatingDescription: The query is

On my screen, I have implemented a query as follows: export const AllFriends: React.FunctionComponent = () => { const navigation = useNavigation(); const { data, error } = useGetMyProfileQuery({ onCompleted: () => { console.log('h ...

Manual mocking in Jest is only effective for the initial function call

In my project, I have created a custom XHR wrapper in utils/xhr.js and I am using Jest manual mocking feature to mock it. However, I am running into an issue where only the first XHR call is being tracked: utils/xhr.js let xhr = { get: function(par ...

Tips on hiding the menu toggler in PrimeNg

Struggling with PrimeNg implementation in my Angular project, I am unable to find a simple solution to hide the menu toggler. Allow me to illustrate my current setup in the first image and what I desire in the second. Let's dive in: View First Image ...