Search code examples
javascriptarraysinput-field

Customize text with input fields


Does anyone know how I would go about to fix the duplicates when clicking on 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>

My search makes me believe i must re-do it all, but I thought I 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.";                        
    });
});

Solution

  • The answer is all about scope of variables. You need to declare your arrays inside your function and not outside.

    Also remove the "+" 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.";                        
    });
    

    Here is your fiddleJs corrected: https://jsfiddle.net/Lwr16wrt/23/