Tips on displaying various colors in selected HTML elements by adding them to an array and showcasing them in a unique way. Issue arises when colors are displayed multiple times upon appending

javascript

function fetchc(){
pclr=document.getElementById("product_color").value;
clr.push(pclr);
var n=clr.length;
$("#colors").show();
 for (var i=0;i<n;i++)
 {
$("#colors").append('<input type="color" value="'+clr[i]+'" disabled>')
 }
 console.log(clr);
}

html

<div class="form-group form-inline">
    <label for="product_color"> Select product Color</label>&emsp;
    <input type="color" class="form-control" id="product_color"placeholder="Product color" style="width: 100px;" onchange="fetchc();">
    <div id="colors" style="display: none;"></div>
  </div>

Although the desired output is achieved, the appending of elements based on array length needs to be adjusted to prevent duplication.

Answer №1

Simply generate an html content and substitute it with the existing colors HTML

var colorArray = []
function fetchColors(){
selectedColor=document.getElementById("product_color").value;
colorArray.push(selectedColor);
var count=colorArray.length;
$("#colors").show();
var htmlCode = "";
 for (var i=0;i<count;i++)
 {
htmlCode += '<input type="color" value="'+colorArray[i]+'" disabled>';
 }

 $("#colors").html(htmlCode);
/*  OR you can simply append without using a loop */
/* $("#colors").append('<input type="color" value="'+selectedColor+'" disabled>')*/
 
 console.log(colorArray);
} 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group form-inline">
    <label for="product_color"> Select product Color</label>&emsp;
    <input type="color" class="form-control" id="product_color"placeholder="Product color" style="width: 100px;" onchange="fetchColors();">
    <div id="colors" style="display: none;"></div>
  </div>

Answer №2

Whenever fetchc() is called, it loops through the elements in the clr array, causing previous selections to be duplicated.

If you have declared clr outside of this function, consider the following example:

const addedColors = [];
function fetchc(){
  const selectedColor = document.getElementById("product_color").value;
  console.log(`selectedColor is ${selectedColor}`);
  addedColors.push(selectedColor);
  addedColors.map((color) => {
    console.log(`adding color ${color}`)
  })

The result will look like this:

selectedColor is #004080
adding color #004080
selectedColor is #400040
adding color #004080
adding color #400040
selectedColor is #400080
adding color #004080
adding color #400040
adding color #400080

As observed, the first color (#004080) was added three times instead of just once.

To avoid this issue, simply append the new color without redundancy (jQuery is not necessary):

function fetchc(){
  const selectedColor = document.getElementById("product_color").value;
  console.log(`selectedColor is ${selectedColor}`);
  const newInput = document.createElement("input");
  newInput.type = 'color';
  newInput.value = selectedColor;
  document.getElementById("colors").appendChild(newInput);
  addedColors.push(selectedColor);
}

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

CSS 3 Shape: "Reverse Circle" or "Hollow Circle"

Trying to create an inverse circle or cut-out circle in CSS has been a challenging task for me. I stumbled upon this insightful answer provided by ScottS. While Scott's code worked like a charm, I am now aiming to achieve a similar effect on the oppo ...

Issue with template updating when utilizing ui-router and ion-tabs in Ionic framework

CODE http://codepen.io/hawkphil/pen/LEBNVB I have set up two pages (link1 and link2) accessible from a side menu. Each page contains 2 tabs: link1: tab 1.1 and tab 1.2 link2: tab 2.1 and tab 2.2 To organize the tabs, I am utilizing ion-tabs for each p ...

JavaScript - Automatic memory management following the execution of functions

After doing some research on garbage collection in JavaScript, I came across information stating that local variables of functions are collected once the function has returned (except for cyclical references which require breaking circles for the GC to fun ...

I'm curious if there is a method to determine the status of a .net required field validator using JavaScript

I am attempting to determine the status of the "required field validators" within an .aspx file. By state, I am referring to whether they are enabled or disabled rather than if their contents are valid or invalid. I am aware that the enabled/disabled sta ...

Obtaining input value when button is clicked

I am currently working on a feature where, upon clicking the Submit button, I aim to retrieve the value entered into the input field in order to update the h1 element. import React from "react"; function App() { const [headingText, setHeadingT ...

When using PWA on an iPhone, the camera feature consistently opens in full screen which makes it difficult to view the HTML button. Adjust

I am currently working on developing a PWA app using the Vue framework that supports camera functionality on both Android and Apple devices. Using mediaDevices, I have successfully enabled the camera and implemented a video stream feature on Android. Addi ...

Save documents in Firebase storage

Currently in the process of developing a web application using Firebase and Angularjs as my frontend tools. Curious to know whether it's feasible to store various file types within the Firebase DB. Could you shed some light on any potential limitatio ...

A particular individual experiencing difficulties executing a script within an HTML form that relies on google.script.run.function()

I've developed an input form that operates within an HTML modal launched from a Google Apps Script in a Google Sheet. This form retrieves values from the sheet, allows users to edit or manipulate them, and then writes the changes back into the sheet u ...

Activate animation as soon as the content comes into view

I've been browsing through numerous posts, but all of them seem to be confusing me. Currently, I am using animate.css within a positioned in the middle of my page. By default, the animation plays when the page loads, but I want it to trigger only wh ...

What methods are available for utilizing "open as" with commands in the shell?

After setting up a folder called my-express-server, I am eager to launch it directly from the shell using Visual Studio Code. To achieve this, I came across the command start [name of the file] -a [the specific path of the program I intend to use to open ...

Explaining the Usage of Nav-pills in Bootstrap v4

I am looking to align my navigation bar across the width of the div. However, I am currently using Bootstrap v4 and the nav-justify class is not available yet. Below is the code snippet: <ul class="nav nav-pills"> <li class="nav-item"> ...

Issue arises when there are several inline <script> tags containing parameters which result in filtered JSON output

As a newcomer to JavaScript, I am faced with the challenge of creating a centralized glossary within a confined educational environment (LMS) that lacks a database or any other facilitating elements. My objective is to develop a script hosted on our applic ...

Creating a dynamic name in TypeScript for an object to be utilized in an onClick event

If I have a TypeScript object declared in my view like this: <script type="text/javascript"> var myTSObject = Module.CustomClass('#someId'); myISObject.bind(); </script> Now, if I need to manage a click event from within the ...

What is the process for uploading a text file into JavaScript?

I'm currently facing an issue with importing a text file from my local computer into JavaScript in order to populate HTML dropdowns based on the content of the file. Despite spending considerable time searching for solutions on stack overflow, I haven ...

Comparison Between React-Redux mapStateToProps and Inheriting Props from ParentsIn the

Excuse my lack of experience, but I am currently delving into the world of react-redux and trying to grasp the concepts as I progress. Situation: In my main component within a react-redux application, I have the following snippet at the end: function map ...

Is it possible to dynamically load records in real time with the help of PHP and jQuery?

I developed a custom system using PHP that allows users to post status messages, similar to a microblog. The system utilizes a database table structured like this: posts_mst ------------------ post_id_pk post_title post_content date_added Initially, I su ...

Switch out the current R shiny htmlwidget data for updated data

Recently, I encountered an issue with a htmlwidget in one of my R shiny applications. Each time the widget render function was called multiple times, it failed to replace the existing data with new data. This bug caused the old data to linger and the new d ...

I am experiencing issues with my for loop not functioning correctly within my On-Click Event in Javascript

Hello, I'm facing a bit of an issue with a for loop inside an On-Click Event. It seems like the loop is only showing me the last value from the array. Can someone please lend a hand here? Below is the code snippet where I have an array with 10 values ...

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

VueJS Router error: The variable $route is undefined

Check out my component: const Vue = require("vue/dist/vue.js"); const qs = require("querystring"); module.exports = Vue.component("Page",function(resolve){ console.log(pageRoute); let id = pageRoute.params.id; fetch("/getPage.json",{ ...