最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery addremove item from array - Stack Overflow

programmeradmin0浏览0评论

I have a checkboxs 3-4 of them, when the user checks the checkbox I want to add the value of the checkbox to the array, if they uncheck the box I want to remove the item from the array, this is what I got so far:

$('ul.dropdown-menu input[type=checkbox]').each(function () {
    $(this).change(function () {

        if ($(this).attr("id") == 'price') {
            if (this.checked) {
                priceArray.push($(this).val());
            }
            else {
                priceArray = jQuery.grep(priceArray, function (value) {
                    return value != $(this).val();
                });
            }
        }
    });
});

Adding the value to the array works perfectly, however removing items results in this error:

Cannot read property 'toLowerCase' of undefined

on this line:

return value != $(this).val();

I have a checkboxs 3-4 of them, when the user checks the checkbox I want to add the value of the checkbox to the array, if they uncheck the box I want to remove the item from the array, this is what I got so far:

$('ul.dropdown-menu input[type=checkbox]').each(function () {
    $(this).change(function () {

        if ($(this).attr("id") == 'price') {
            if (this.checked) {
                priceArray.push($(this).val());
            }
            else {
                priceArray = jQuery.grep(priceArray, function (value) {
                    return value != $(this).val();
                });
            }
        }
    });
});

Adding the value to the array works perfectly, however removing items results in this error:

Cannot read property 'toLowerCase' of undefined

on this line:

return value != $(this).val();
Share Improve this question edited Apr 17, 2017 at 20:50 Julian 36.9k24 gold badges135 silver badges191 bronze badges asked Apr 17, 2017 at 20:45 user979331user979331 12k83 gold badges248 silver badges451 bronze badges 5
  • Provide whole code. – kind user Commented Apr 17, 2017 at 20:46
  • whole code provided – user979331 Commented Apr 17, 2017 at 20:47
  • Where's html code? – kind user Commented Apr 17, 2017 at 20:48
  • Without the code resulting in error, what that means is the left operand being undefined and cannot have toLowerCase applied to it. Please provide this code, otherwise this is pure speculation at best. – Frederik.L Commented Apr 17, 2017 at 20:54
  • why don't you just loop over the checkboxes and get the checked ones each time instead of adding/removing with loops. – epascarello Commented Apr 17, 2017 at 20:58
Add a ment  | 

5 Answers 5

Reset to default 4

Run the code snippet and check

<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var priceArray=[];
  $(document).ready(function(){
  $('input[type=checkbox]').each(function () {
    $(this).change(function () {
            if (this.checked) {
                priceArray.push($(this).val());
               $("#displayarray").html("array=[" + priceArray+"]");
            }
            else {
               var index = priceArray.indexOf($(this).val());
               if (index > -1) {
                  priceArray.splice(index, 1);
                }
                $("#displayarray").html("array=[" + priceArray+"]");
            }
    });
});
  
  });
</script>
<input type="checkbox" value="box1"/>box1
<input type="checkbox" value="box2"/>box2
<input type="checkbox" value="box3"/>box3
<input type="checkbox" value="box4"/>box4
<br/>
<div id="displayarray"></div>

Replace

priceArray = jQuery.grep(priceArray, function (value) {
    return value != $(this).val();
});

By

val = $(this).val();
priceArray = jQuery.grep(priceArray, function (value) {
    return value != val;
});

Don't forget the scope where your are in the callback function.

You can try using filter instead of $.grep:

var values = [];

$("input").on("change", function() 
{
  var $this = $(this);
  
  if ($this.is(":checked")) 
  {
    values.push($this.val());
  }
  else 
  {
    values = values.filter(x => x != $this.val());
  }
  
  console.log(values);
});
<script src="https://ajax.googleapis./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" />

filter() is a native function, I prefer using built-in function rather than 3rd party's, IMO. Also, avoid binding events within loops like this:

$('ul.dropdown-menu input[type=checkbox]').each(function () {
    $(this).change(function () {

Use this method:

$('ul.dropdown-menu').on('change', 'input[type=checkbox]', function() { ...

This will work even if checkbox is dynamically added.

You could do this very cleanly with a functional style

<div class="checkboxes">    
  <input type="checkbox" value="1" />
  <input type="checkbox" value="2" />
</div>

And

(function() {
    $(".checkboxes input[type=checkbox]").on("click", function() {
        var x = $(".checkboxes input[type=checkbox]:checked").map(function(a,b) {
        return parseFloat(b.value);
      }).toArray();
      console.log(x)
    });
})();

I had a similar situation and I was able to overe it in the following way :

My jQuery :

$(document).ready(function(){
    $("#dataFilterForm").on("input", function() {
        var values = '';
        var boxes = $('input[name=vehicle]:checked');
        boxes.each(function(b){
            values = values + boxes[b].id + ', ';
        });
        $('#filterResult').text(values.substring(0, values.length-2));
    });
});

My HTML :

<form id="dataFilterForm">
    <input type="checkbox" id="Filter1" name="vehicle" value="Bike">
    <label for="Filter1">Filter1</label><br>
    <input type="checkbox" id="Filter2" name="vehicle" value="Car">
    <label for="Filter2">Filter2</label><br>
    <input type="checkbox" id="Filter3" name="vehicle" value="Boat">
    <label for="Filter3">Filter3</label><br>
</form>
<p>Result : </p>
<p id="filterResult"></p>
发布评论

评论列表(0)

  1. 暂无评论