Piyush Kumar
Piyush Kumar

Reputation: 541

How to set checkbox value equal to Javascript object

I want to add checkboxes for each item listed , I am using Each loop to render the list so , when I check the checkbox for that particular list item and I move to cart then I want to get that item object as the value of checkbox.

{{#each list}}
    <input type="checkbox" name="list" >
    <p>{{this.title}}</p>
{{/each}}
<button class="btn btn-primary" id="addToCart" >ADD TO CART</button>

Now when I click the button I want it to return the object for which the checkbox was checked(i.e when list item 1 is checked then the button click should return list item 1 and so on...)

Note: I want to set the value of the checkbox equal to list item object.

Upvotes: 1

Views: 3150

Answers (1)

Koen Morren
Koen Morren

Reputation: 1363

You will need to set the value of the checkbox to some unique identifier of the item in the list:

{{#each list}}
  <input type="checkbox" name="list" value="{{this.id}}" id="{{'list' + this.id}}" />
  <label for="{{'list' + this.id}}">{{this.title}}</label>
{{/each}}

(Using a label instead of paragraph allows the user to also click on the text to select or deselect the checkbox, without any javascript needed)

Then you could use the following code, in the call triggered by the button, to get the list of all checked checkboxes:

$.each($("input[name='list']:checked"), function() {
  //push the items to list or whatever you want
});

You could try to set the entire object as the checkbox value, but I haven't tried that and don't know the impact:

<input type="checkbox" name="list" value="{{this}}" id="{{'list' + this.id}}" />

Upvotes: 1

Related Questions