0

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.

1
  • Can you please share your html or a fiddle, too? Commented Jun 22, 2017 at 16:28

2 Answers 2

1

You had some incorrect logic dealing with your AND appending. Take a look below.

$(document).ready(function() {
  var lastChecked;
  var $checks = $('input:checkbox').click(function(e) {
    var numChecked = $checks.filter(':checked').length;
    var text = $('#text_query');
    text.val('');
    $(":checkbox:checked").each(function() {
      console.log($(this).val());
      text.val($(this).val() + ' AND ' + text.val());
    });
    var str = text.val();
    text.val(str.substring(0, str.length - 4));
    lastChecked = this;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
<input type="checkbox" value="4">
<input type="checkbox" value="5">
<input type="checkbox" value="6">
<input type="checkbox" value="7">
<input type="checkbox" value="8">
<input type="checkbox" value="9">
<br/>
<input type="text" id="text_query">

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

    var text = $('#text_query');
     text.val(text.val('AND'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.