Swap out the string variable when it is modified

To generate a string inside the "code" variable that combines the selected image values, the final code should appear similar to: "test1/A=1a/B=1b" or "test2/A=1b/B=1a", etc. If the user modifies icon "A," it should replace the value in the code instead of adding to it like in the example below.

Please refer to the snippet below for more details.

let code;

$(".selectIco").click(function(){
  $(".iconSelect").html("");
  $(this).clone().appendTo(".iconSelect");
})

let thisIcon;
$(".clone").on("click", function() {
  thisIcon = $(this);
  $(".iconSelect").html("");
    $(".icons").slideDown("1000");

function imagePicker() {
  $(".selectIco").on("click", function() {
    $(".iconSelect").html("");
    $(this).clone().appendTo(".iconSelect");
    $(thisIcon).html("");
    $(".iconSelect img").clone().appendTo(thisIcon);
  })
}
imagePicker();
    })

$(".test1").click(function(){
  code = "test1";
  console.log(code);
})
$(".test2").click(function(){
  code = "test2";
  console.log(code);
})

//code
  $('.cloner1').bind("DOMSubtreeModified",function(){
    if ($(this).children("img").length > 0 ) {
      iconA = $(this).children('.selectIco').attr('value');
      code += 'A=' + iconA;

      console.log("export of code = " + code);

    }
  });
    $('.cloner2').bind("DOMSubtreeModified",function(){
    if ($(this).children("img").length > 0 ) {
      iconA = $(this).children('.selectIco').attr('value');
      code += 'B=' + iconA;

      console.log("export of code = " + code);

    }
  });
.iconSelect {
  height: 90px;
  width: 90px;
  border: 2px solid blue;
}
.clone {
  float:left;
  margin-right: 10px;
  height:120px;
  width: 120px;
  background-color: pink;
}
.icons {
  display: none;
}
.test1, .test2 {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>first</h1>
<div class="test1">clickme</div>
or
<div class="test2">clickme</div>
<br/>

<h1>second</h1>
<div class="clone cloner1">A</div>
<div class="clone cloner2">B</div>

<div class="iconSelect"></div>
<div class="icons">
  <img  class="selectIco" src="https://upload.wikimedia.org/wikipedia/en/thumb/9/9f/Twitter_bird_logo_2012.svg/100px-Twitter_bird_logo_2012.svg.png" value="/1a">
  <img class="selectIco" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ab/Gmail_Icon.svg/100px-Gmail_Icon.svg.png" value="/1b">
</div>

Answer №1

Make a simple adjustment to your code by changing the assignment operator from += to = in the last two instances, and everything should work smoothly:

let code;

$(".selectIco").click(function() {
  $(".iconSelect").html("");
  $(this).clone().appendTo(".iconSelect");
})

let thisIcon;
$(".clone").on("click", function() {
  thisIcon = $(this);
  $(".iconSelect").html("");
  $(".icons").slideDown("1000");

  function imagePicker() {
    $(".selectIco").on("click", function() {
      $(".iconSelect").html("");
      $(this).clone().appendTo(".iconSelect");
      $(thisIcon).html("");
      $(".iconSelect img").clone().appendTo(thisIcon);
    })
  }
  imagePicker();
})

$(".test1").click(function() {
  code = "test1";
  console.log(code);
})
$(".test2").click(function() {
  code = "test2";
  console.log(code);
})

//code
$('.cloner1').bind("DOMSubtreeModified", function() {
  if ($(this).children("img").length > 0) {
    iconA = $(this).children(".selectIco").attr("value");
    code = "A=" + iconA;

    console.log("export of code = " + code);

  }
});
$('.cloner2').bind("DOMSubtreeModified", function() {
  if ($(this).children("img").length > 0) {
    iconA = $(this).children(".selectIco").attr("value");
    code = "B=" + iconA;

    console.log("export of code = " + code);

  }
});
.iconSelect {
  height 90px;
  width: 90px;
  border: 2px solid blue;
}

.clone {
  float: left;
  margin-right: 10px;
  height: 120px;
  width: 120px;
  background-color: pink;
}

.icons {
  display: none;
}

.test1,
.test2 {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>first</h1>
<div class="test1">clickme</div>
or
<div class="test2">clickme</div>
<br/>

<h1>second</h1>
<div class="clone cloner1">A</div>
<div class="clone cloner2">B</div>

<div class="iconSelect"></div>
<div class="icons">
  <img class="selectIco" src="https://upload.wikimedia.org/wikipedia/en/thumb/9/9f/Twitter_bird_logo_2012.svg/100px-Twitter_bird_logo_2012.svg.png" value="/1a">
  <img class="selectIco" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ab/Gmail_Icon.svg/100px-Gmail_Icon.svg.png" value="/1b">
</div>

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

Elevate your Material UI Avatar with an added level of

Attempting to give a MUI Avatar component some elevation or shadow according to the documentation provided here. <Avatar alt="Cindy Baker" src="/static/images/avatar/3.jpg" /> Enclosing the Avatar within a paper or Card element increases the size o ...

Displaying a pop-up window containing information retrieved from the console output

Upon user input in the form on my web application, an scp and ftp process is initiated that takes around 2-3 minutes to complete. The result page consequently experiences a similar delay in loading. To enhance user experience and provide real-time updates ...

Struggling to add a line break in my code

class Test extends React.Component{ state={name: "John", numTimes: 2}; render() { let output = "" for (let i = 1; i <= this.state.numTimes; i++) { let evenOdd = i % 2 if (evenOdd === 0) { output += i + ". Hello " + this.state.name + ...

An in-depth guide on implementing debounce functionality for `keyup` events in Vue.js

I am attempting to detect when the user begins typing and stops typing using the debounce function. I experimented with Lodash and Underscore.js. On my textArea v-on:keyup="handler($event)" handler: function(e) { ...

Enhancing Bootstrap Date Picker with Custom Buttons: A Tutorial

I am attempting to enhance the datepicker functionality by including a custom button, similar to the today button. My goal is to insert a button at the bottom of the calendar each month. This button will be named "End of the month" and will display the c ...

What is the reason behind the perpetual hiding of the button?

<div class="app__land-bottom" v-if="isVisible"> <a href="#projects"> <img ref="arrowRef" id="arrow" src="./../assets/down.png" alt srcset /> </a> </div> When ...

javascript The event handler is not functioning properly for the dynamically loaded AJAX content

I am facing an issue with adding a JavaScript event listener to a dynamically loaded div via AJAX. Below is my code snippet: var QuantityMiniCart = function() { var infor = document.querySelectorAll( '.mini-cart-product-infor' ); if ( ...

Tips for accessing nested JSON values using Selenium

Here is a JSON snippet to work with: "ACCOUNT": { "AmountDue": "$36,812.99", "OutstandingBalance": "$27,142.27", "StatementTotal": "$9,670.72", "StatementDate": "12/6/2018", "DueByDate": "12/23/2018", ...

What could be causing a react element to fail to update?

I'm currently working on a React component that interacts with a MaterialUi text form. The component utilizes a useState hook to update based on the input received. My goal is to have another variable update when the form is submitted, which will be d ...

What is the best way to attach information to a chart prior to the jquery dialog box appearing?

I am currently working on a web application that interacts with an Azure database. The goal is to create a graph based on user selections from a radio list and two inputted time parameters. The intention is to showcase this graph in a jQuery dialog box tha ...

Utilize NodeJS API to convert a base64 data string into a downloadable PDF file

My NodeJS API is set up to communicate with another API and fetch a data object in the form of a Base64 string. The client making the API call needs to be able to download a PDF file generated from this base64 data. What is the best way to return the dat ...

Elevate your tooltips with Bootstrap 5: enabling hoverable tooltips and clickable links

At times, you may want to include clickable links in tooltips. I recently encountered this issue while using Bootstrap 5 and had trouble finding a solution. After some trial and error, I finally figured it out and wanted to share my findings. The standard ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

"Having trouble implementing sorting functionality on a click event in a React application with Material-UI table

Default behavior displays data in ascending order. Clicking on the table header should toggle between descending and ascending orders. Load Data in ascending order -> On click, change to descending order -> Again on click, change to ascending -> ...

Showcasing a dynamic image as a task is being completed within a JavaScript function

Is there a way to show a loading image while waiting for a JavaScript function to finish? <script type="text/javascript"> function create() { //Perform operation } </script> I am looking for a solution to display a loading image until ...

Obtaining values from keys in React list items

getEmployeeCredits(id) { if (this.state.company_roles) { return this.state.company_roles.map(function (cr, i) { if (cr.id === id) { return cr.assigned_credits } }.bind(thi ...

How do I dynamically create a new table row every time a div is clicked using jQuery?

I want to dynamically generate a new table row each time a div is clicked, ensuring that only one row is created per click even if the same div is clicked twice. HTML <div class="block div1"></div> <div class="block div2"></div> & ...

JavaScript: what is the method to add a paragraph when the condition is not met?

I am currently working on a project that involves checking if a student is actively engaged in an online journal. This is done by tracking the student's progress using a unique userId. If the student's userId is not found in the JSON data returne ...

What's the point of repeatedly confirming prompts?

I am using Jquery ajax call to delete data from my HTML table. Everything works fine, but the alert message keeps showing repeatedly. What could I be doing wrong? Delete button "<a href='#my_modal' class='delete-Record'>Del ...

Leverage the power of Vue Nuxt Auth to activate authentication middleware on a route-by-route

Is there a way to implement auth middleware for individual routes using Class Components? How can I achieve the same functionality as this: <script> export default { middleware: 'auth' } </script> The following method does n ...