Enter your own text into the input fields to create a personalized message

Is there a way to eliminate duplicates when checking the checkboxes?

<label><input type="checkbox" data-bValue="100" data-sValue="sV1" data-nValue="nV1" name="layers"> 100</label><label><input type="checkbox" data-bValue="200" data-sValue="sV2" data-nValue="nV2" name="layers"> 200</label><label><input type="checkbox" data-bValue="300" data-sValue="sV3" data-nValue="nV3" name="layers"> 300</label><label><input type="checkbox" data-bValue="400" data-sValue="sV4" data-nValue="nV4" name="layers"> 400</label><label><input type="checkbox" data-bValue="500" data-sValue="sV5" data-nValue="nV5" name="layers"> 500</label><label><input type="checkbox" data-bValue="600" data-sValue="sV6" data-nValue="nV6" name="layers"> 600</label><label><input type="checkbox" data-bValue="700" data-sValue="sV7" data-nValue="nV7" name="layers"> 700</label><h1 id="render"></h1>

I've searched for solutions, but before redoing it all, I wanted to ask here first.

Fiddle: https://jsfiddle.net/swedoc/Lwr16wrt/

    $(document).ready(function() {

    var scents = [];
    var notes = [];
    var theRender = document.getElementById("render"); 

    $("input[name='layers']").on('click', function(){ 

                $.each($("input[name='layers']:checked"), function(){            
                    scents.push($(this).attr("data-sValue"));
                });        

                $.each($("input[name='layers']:checked"), function(){            
                    notes.push($(this).attr("data-nValue"));
                });

                    theRender.innerHTML 
                    += "You’ve created a<br>" 
                    + scents.join(', ').replace(/,(?!.*,)/gmi, ' and') + " sValue with " 
                    + notes.join(', ').replace(/,(?!.*,)/gmi, ' and') + " nValue.";                        
    });
});

Answer №1

Understanding the scope of variables is crucial for this answer. It's important to declare your arrays inside the function rather than outside of it.

Additionally, make sure to eliminate the "+" sign from your innerHTML +=.

$("input[name='layers']").on('click', function(){ 
    var scents = [];
    var notes = []; 

    $.each($("input[name='layers']:checked"), function(){            
        scents.push($(this).attr("data-sValue"));
    });        

    $.each($("input[name='layers']:checked"), function(){            
        notes.push($(this).attr("data-nValue"));
    });

    theRender.innerHTML = "You’ve created a<br>" 
      + scents.join(', ').replace(/,(?!.*,)/gmi, ' and') + " sValue with " 
      + notes.join(', ').replace(/,(?!.*,)/gmi, ' and') + " nValue.";                        
});

The corrected version of your fiddleJs can be found here: https://jsfiddle.net/Lwr16wrt/23/

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

Using Jquery to create interactive and dynamic webpage elements

I am struggling with a paragraph containing words in a span that are editable upon clicking. The content needs to be dynamically called, but my current approach is not effective. Can anyone provide a solution or a better way to achieve this? Feel free to ...

Transferring form data through AJAX for uploading files

My current task involves uploading an image using form data with ajax. I have successfully tested the code below and it is saving the image on my local machine. <form ref='uploadForm' id='uploadForm' action='/tab10/uploadImage& ...

Guide on showing a URL within an onclick event using the jQuery Append method

My method involves using AJAX to upload images and then displaying the uploaded image by utilizing the jQuery append function. The challenge comes when I try to add an onclick event to the specific image tag. To tackle this, I start by creating a JavaScri ...

Retrieve a div element using two specific data attributes, while excluding certain other data attributes

Here are some examples of divs: <div id="1" data-effect-in="swing" data-effect-out="bounce"></div> <div id="2" data-effect-in="swing"></div> <div id="3" data-effect-out="swing"></div> <div id="4" data-effect-out data ...

Infinite loop caused by iterating through an array using a for loop

I'm having trouble with a piece of code that should clear an array of characters when the enter key is pressed, but instead, it's stuck in an infinite loop and I can't figure out why. The code works by adding a new character to a character ...

Retrieving the initial JSON key

Is it possible to retrieve the name of the initial property within a JSON object? I am interested in achieving something similar to this: var firstProp = jsonObj[0]; edit: The JSON object I have contains categories with arrays of image URLs. For example ...

Does ReactJS demonstrate ingenuity when it comes to calling the render method?

Despite not utilizing any of the props supplied to the component, will it still re-render when the props change? class MyComponent extends React.Component { constructor(props) { super(props); const { propValue } = props; // do something wi ...

Capturing keydown events exclusively in the topmost layer of the HTML document

Currently, I am developing a web application that includes an underlying HTML file with some JavaScript functionality that I cannot modify. In my code, I create a layer on top of this page using CSS with z-index: 1000;. However, I am facing an issue where ...

Struggling to set up a css3 keyframe slide effect and seeking help to properly configure it. Check out the Fiddle for more details

I am looking to create a responsive version of the animation in this fiddle (link provided below). I want the animation to be 100% wide and have a height of 500px. However, when I adjust the width to 100%, it causes issues at the end of the animation. Can ...

Minimize the visibility of the variable on a larger scale

I have a nodejs app where I define global variables shared across multiple files. For example: //common.js async = requires("async"); isAuthenticated = function() { //... return false; }; //run.js require("common.js"); async.series([function () { i ...

Tips for resizing images to fit the parent container dimensions

After uploading an image, I needed to adjust its dimensions. The original image was 450x700, while the parent container was 400x400. Using 'object-fit' helped fit the image to its parent container while maintaining its aspect ratio. However, I r ...

Can you help me identify the issue with my current Jade for loop implementation?

Here is my full loop code written in Jade: block content div(class='row') div(class='col-lg-12') h1(class='subject') 로또라이 div(class='row') div(class='col-lg-8') - for (var ...

incapable of executing a rest request

Hello everyone, I am trying to make a REST call and redirect the output to a text area in HTML. Below is the code I have written for this purpose. Please review it and let me know if there are any mistakes. Additionally, could you please explain how to a ...

Unable to send messages despite successful connection through Sockets.io

My Java Server is set up to listen for messages from an Ionic 2 Client using Sockets.io. The server can successfully send messages to the client, but I am facing issues with getting the client to send messages back to the server. For example, when the jav ...

Using vuex-class to interact with Vuex in non-Vue components

Is it possible to access Vuex outside of a Vue component using vuex-class? In a typical scenario, the process is quite straightforward: // some JS file import store from './../store'; // path to Vuex store store.commit('ux/mutationName&ap ...

Error: Preflight request returned a 405 HTTP status code when querying Ionic + CI backend

I am currently working on my first app using ionic with a codeigniter backend. However, I am encountering the "Response for preflight has invalid HTTP status code 405" issue in ionic + CI backend. Can anyone help me solve this problem? This is my controll ...

Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter: const density = ' .:░▒▓█' //const density = ' .tiITesgESG' //let geist; let video let asciiDiv let playing = false let ...

Comparison of jQuery, AngularJS, and Node.js

I'm a beginner in web development and I have some basic knowledge: HTML - structure of websites CSS - design aspect JavaScript - for adding interactivity Now, what exactly is jQuery, AngularJS, and Node.js? Upon researching, I discovered that jQue ...

Display JSON values from a successful AJAX call within an HTML dropdown menu

Having an html form with multiple drop down selections, I have utilized the same form for data editing, To edit data in a specific row of the table, I implemented an AJAX request. Once a row is selected and the user clicks on edit, the AJAX call retrieves ...

How can I clear all checkboxes when the checkbox with id "checkAll" is selected?

Is there a way to uncheck all checkboxes when the checkbox with id="checkAll" is checked? In my demonstration, when a user checks the checkbox with id="checkAll", all checkboxes are also marked as checked. However, I actually want it so that when the che ...