1

I have checkboxes on page and i want to POST only checked values onchange each checkbox

$(function () {
    $('.list input').change(function (e) {
        //e.preventDefault();
        var favorite = [];
        $.each($(".list input[type='checkbox']:checked"), function () {
            favorite[$(this).attr("name")].push = $(this).val();
        });

        var str;
        str = $.param(favorite);

        $.ajax({
            url: '/schema.asp',
            type: 'POST',
            data: str,
            dataType: 'text',
            success: function (response) {
                alert(response);
            }
        });
    });
});

But I cant do right syntax to push checked to array

$.each($(".list input[type='checkbox']:checked"), function () {
    favorite[$(this).attr("name")].push = $(this).val();
});

Please show the right way.

$(this).attr("name") can vary from (Make[],Model[],Year()) and must be a string

SOLVED:

As nobody answer with full answer, this is finall working code

    $(function () {
        $('.list input').change(function (e) {
            //e.preventDefault();
            var favorite = {};
            $.each($(".list input[type='checkbox']:checked"), function(){ 
            if(typeof(favorite[$(this).attr("name")]) == 'undefined'){
                favorite[$(this).attr("name")] = [];
            }           
            favorite[$(this).attr("name")].push($(this).val());
        });

            var str;
            str = $.param(favorite);

            $.ajax({
                url: '/schema.asp',
                type: 'POST',
                data: str,
                dataType: 'text',
                success: function (response) {
                    alert(response);
                }
            });
        });
    });
Dmitrij Holkin
  • 1,995
  • 3
  • 39
  • 86
  • possible duplicate of [Insert Item into Array at a Specific Index](http://stackoverflow.com/questions/586182/insert-item-into-array-at-a-specific-index) – fsacer Jun 09 '15 at 10:11

2 Answers2

4

push is a function to be called, not a property to be set

var favorite = {};
$.each($(".list input[type='checkbox']:checked"), function(){ 
    if(typeof(favorite[$(this).attr("name")]) == 'undefined'){
        favorite[$(this).attr("name")] = [];
    }           
    favorite[$(this).attr("name")].push($(this).val());
});

Also, note above you need to check if that property for the object has been set or not in order to initialize it as an array.

$('.list input').change(function(e) {
  //e.preventDefault();
  var favorite = [];
   $.each($(".list input[type='checkbox']:checked"), function(){ 
                if(typeof(favorite[$(this).attr("name")]) == 'undefined'){
                    favorite[$(this).attr("name")] = [];
                }           
                favorite[$(this).attr("name")].push($(this).val());
            });
  console.log(favorite);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul class="list">
  <li>
    <input type="checkbox" name="one" value="1" />
  </li>
  <li>
    <input type="checkbox" name="two" value="2" />
  </li>
  <li>
    <input type="checkbox" name="one" value="1" />
  </li>
  <li>
    <input type="checkbox" name="two" value="2" />
  </li>
  <li>
    <input type="checkbox" name="one" value="1" />
  </li>
</ul>
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • @DmitrijHolkin, it is giving that exception because at that point in execution `favorite[$(this).attr("name")]` **is** undefined – AmmarCSE Jun 09 '15 at 10:12
  • @DmitrijHolkin, it would have happened if you tried any other property like `favorite[$(this).attr("name")].wakawaka = 1;` – AmmarCSE Jun 09 '15 at 10:13
  • Uncaught ReferenceError: favorite is not defined – Dmitrij Holkin Jun 09 '15 at 10:22
  • `$(this).attr("name")` must be a number (or string number) like `1` or `"1"`. If `$(this).attr("name")` is a string like `"foo"` or `"01"` this code not works. – Frogmouth Jun 09 '15 at 10:23
  • 1
    if `$(this).attr("name")` is a string like `foo` `favorite` must be an object `{}` not an array `[]` – Frogmouth Jun 09 '15 at 10:26
  • Sigh, somebody downvoted, do they care to explain why? – AmmarCSE Jun 09 '15 at 10:28
  • I edit your answer to add a short version of your code and the correct definition of `favorite`. UPVOTE. – Frogmouth Jun 09 '15 at 10:47
  • @Frogmouth, I appreciate the upvote and edit. However, I took the first part `var favorite = {};` but left the last part as I beleive this is more readable. – AmmarCSE Jun 09 '15 at 10:48
1

use map() in jquery .Translate all items in an array or object to new array of items.

favorite = $(".list input[type='checkbox']:checked").map(function () {
    var obj = {};
    obj[$(this).attr("name")] = this.value;
    return obj;

}).get();

Fiddle Demo

Balachandran
  • 9,567
  • 1
  • 16
  • 26