vendredi 9 octobre 2020

Javascript. Building a string from checkbox values and filtering by id

I have a series of checkboxes with the ID 'colour' and a text field with id 'result-colour'.

I have this script which will populate the text field with whatever is 'checked'. This works fine!

var arr = []
    $(":checkbox").each(function(){
       if($(this).is(":checked")){
         arr.push($(this).val())
       }
    })
    var vals = arr.join(", ")
    var str = vals
  
    $('#result-text-colour').text(str);

But I also have other checkboxes on the same page (with different id's) but they also appear in the string

I tried to filter my code with:

var checkboxElementClicked = (this.id); 
//alert(checkboxElementClicked);
if (checkboxElementClicked == 'colour'){

var arr = []
    $(":checkbox").each(function(){
       if($(this).is(":checked")){
         arr.push($(this).val())
       }
    })
    var vals = arr.join(", ")
    var str = vals
  
    $('#result-text-colour').text(str);
};

which appeared to work, until I click a 'colour checkbox' and then everything that was checked appears in the string...

Can anyone help me filter out everything else apart from colour id's to go into my string?

Thanks very much!




Aucun commentaire:

Enregistrer un commentaire