Newbi Newbi - 7 months ago 17
Javascript Question

Javascript : function bind.click & for each checkbox

I have some combo box, every combo box have value and group by class & ID

<input type="checkbox" value="A" class="box-1" id="ID_1">
<input type="checkbox" value="B" class="box-1" id="ID_1">
<input type="checkbox" value="C" class="box-2" id="ID_2">
<input type="checkbox" value="D" class="box-2" id="ID_2">


If user click button, then check each box, if this checked, store value & ID to variable.

EDIT :

JS :

$('#button').bind('click', function() {

var box = '';
var p =0;
var count = document.getElementById("count").value; // for count total class checkbox

for(d=1; d <= count; d++){

p = 0;
$('.box-' + d).each(function(item){ // each box-1/2/3
if(this.checked){
if(p == 0)
{
var name = this.value.replace(/\s/g, '');
box += '&' + ($(this).attr('id')) + '=' + '&' + encodeURIComponent(name).toLowerCase());
p+=1;
alert(box);
}
else
{
var href = ($(this).attr('id')) + '=';
var name_2 = this.value.replace(/\s/g, '');
box += href + '&' + encodeURIComponent(name_2).toLowerCase());
p+=1;
}
}
});
}

alert(box);
//location = url;
});


example case :
the
checked
combo box is
A & D

what i expect is
&ID_1=&AID_2=&D


when i try alert it's display nothing(''), but when i try alert(box) inside if( p== 0) it's have result
1&ID_1=A
and
0&ID_2=&D
.

Try check this here

Answer
 change your code into like this

    $('#button').bind('click', function() {

    var boxval="";
    //&ID_1=&AID_2=&D
    $("input[class^='box-']").each(function(){

    if($(this).is(':checked'))
    {

    boxval += $(this).attr('id') +'=&' + $(this).attr('value');
    }
    });

    if(boxval !='')
    alert(boxval)
    else
    alert("nothing will selected");

    });




 below is the working fiddle

https://jsfiddle.net/17hxsa9r/

Comments