jeudi 22 juin 2017

jQuery - Add a string to textbox if more than one checkbox is checked and for each checkbox

I have over 25 check-boxes. So far I have it when an item is check the value goes inside a textbox. What I am trying to do is... After the first check box is check and it is value is then entered in a textbox below... Everything else checked needs to add a string of " AND " before each value that is checked. My script is below...

    <script>
        $(document).ready(function(){
            var lastChecked;
            var $checks = $('input:checkbox').click(function(e) {
                var numChecked = $checks.filter(':checked').length;
                    if (numChecked > 1 ) {
                        $(":checkbox:checked").each(function(){
                            var text = $('#text_query');
                            text.val(' AND' + text.val());
                    });                                 
                }
                lastChecked = this;
            });
        }); 
    </script>  

The problem that I am having is all the "And"s are all showing up in front of all products and I am recieving an extra "AND" from the first product I checked inside a text box. Example

AND AND AND Product_1 Product_2 Product_3

It should look like this...

Product_1 AND Product_2 AND Product_3

So what Am I missing. Any help is appreciated.




Aucun commentaire:

Enregistrer un commentaire