Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array.push() do not add but replace it

I have some checkboxes styled with bootstrapSwitch. I wrote a script that have to add value of checkbox to an array when bootstrapSwitch state is true.

This is my code :

$('input[name^=skill]').on('switchChange.bootstrapSwitch', function (event, state) {

    //alert(state);
    //var s = [];

    var s = new Array();

    if( state === true )
    {
        //var value = $(this).val();
        s.push( $(this).val() );

        console.log(s);//(value)

    }

        console.log(s);//(value)
});

But surprisingly push method replace the value and my s array always have one index.

Would you please let me know why is that?

Thanks in Advance

like image 614
Kiyarash Avatar asked Apr 18 '16 10:04

Kiyarash


2 Answers

var s = new Array();

Define this out of the handler function.

It's always 1 because you're recreating it everytime.

like image 184
Alok Patel Avatar answered Oct 05 '22 11:10

Alok Patel


var s = new Array();// this line should be out side of function. so it will not be new object everytime

so try this

var s = new Array();// this line should be here. so it will not be new object everytime

$('input[name^=skill]').on('switchChange.bootstrapSwitch', function (event, state) {

    //alert(state);
    //var s = [];

    var s = new Array();

    if( state === true )
    {
        //var value = $(this).val();
        s.push( $(this).val() );

        console.log(s);//(value)

    }

        console.log(s);//(value)
});
like image 45
sangram parmar Avatar answered Oct 05 '22 12:10

sangram parmar