0

I have a list of check boxes with different values.

<input type="checkbox" value="55" id="myId"> <input type="checkbox" value="65" id="myId"> <input type="checkbox" value="75" id="myId"> <input type="checkbox" value="85" id="myId"> <input type="checkbox" value="95" id="myId"> 

When I'm getting those values using js that will take only value=55 only. It is due to the same id="myId"

var x = ""; $("input[type='checkbox']").change(fucntion(){ if(this.checked){ x = x+","+x; } }); 

When run that will load only 55 values like-: 55,55,55,55

1

3 Answers 3

3

Attribute id should be unique. You can use an array instead of string variable. Then simply add or remove item based on the check box status:

var x = []; $("input[type='checkbox']").change(function(){ if(this.checked){ x.push(this.value); } else { var index = x.indexOf(this.value); x.splice(index, 1); } console.log(x.join(',')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" value="55" id="">55 <input type="checkbox" value="65" id="">65 <input type="checkbox" value="75" id="">75 <input type="checkbox" value="85" id="">85 <input type="checkbox" value="95" id="">95

Sign up to request clarification or add additional context in comments.

2 Comments

what's with pop(this.value)? pop() doesn't use arguments
That's not how pop works. It always removes last element in array
1

First of all don't use multiple same ids on your page, id should be unique on entire page, try data attributes instead

$("input[type='checkbox']").change(function(){ var x = ""; $("[data-id=myId]").each(function(){ if(this.checked){ x = x + $(this).val() + ","; } }); console.log(x); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" value="55" data-id="myId"> <input type="checkbox" value="65" data-id="myId"> <input type="checkbox" value="75" data-id="myId"> <input type="checkbox" value="85" data-id="myId"> <input type="checkbox" value="95" data-id="myId">

1 Comment

Or use name="myarray[]" instead of id.
1

If selection order isn't important can map() the checked values to new array every change

Your string concatenation approach doesn't take into account unchecking a previously checked input

$(':checkbox').change(function(){ var vals = $(':checkbox:checked').map(function(){ return this.value }).get() console.log(vals.join()) }) // insert values as text for demo .wrap(function(){ return $('<label>',{text:this.value}) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" value="55" > <input type="checkbox" value="65" > <input type="checkbox" value="75"> <input type="checkbox" value="85" > <input type="checkbox" value="95" >

Note that ID's must be unique in a page

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.