0

In check box list generated by Php foreach, i try to limit how many check box i can check and unchecked the last clicked.

var limit = 1;
    var chkArrayCheckBoxOne = [];

 $('input.catV').on('change', function(evt) {
        chkArrayCheckBoxOne.push($(this).val());
        if($(this).siblings(':checked').length >= limit) {
            var TagO = chkArrayCheckBoxOne[0];

                console.log(TagO);

            $('input[value='+TagO+']').prop('checked', false);
            chkArrayCheckBoxOne[0] = $(this).val();
        }
    });

This work fine if the value have no space. If the value is "Jhon" my limit work but if the value is "Jhon Doe" i get :

Syntax error, unrecognized expression: input[value=Jhon Doe]

Somebody have an idee ?

  • Possible duplicate of [jQuery: dealing with a space in the id attribute](https://stackoverflow.com/questions/6802765/jquery-dealing-with-a-space-in-the-id-attribute) – user4020527 Jan 13 '18 at 04:35

1 Answers1

1

You just need to wrap the value of the input with double quotes when you use the attribute selector, like this:

var limit = 1;
var chkArrayCheckBoxOne = [];

$('input.catV').on('change', function (evt) {
  chkArrayCheckBoxOne.push($(this).val());
  if($(this).siblings(':checked').length >= limit) {
    var TagO = chkArrayCheckBoxOne[0];
    $('input[value="'+TagO+'"]').prop('checked', false); // Value wrapped in double quotes
    chkArrayCheckBoxOne[0] = $(this).val();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="catV" type="checkbox" value="John" /> John
<input class="catV" type="checkbox" value="John Doe" /> John Doe
kakamg0
  • 1,096
  • 5
  • 12