0

Can you please take a look at this code and let me know wha I am not able to create checkbox from the array of items

 var items: ['item1', 'item2', 'item3', 'item4', 'item5', 'item6'];
for (i = 0; i < items.length; i++) {
   $('#checks').appendTo('<input type="checkbox">');
}

.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checks"> </div>

1 Answer 1

1

You've got a couple problems. You should use append instead of appendTo and you've got an errant : that should be an =.

var obj = { items : ['item1', 'item2', 'item3', 'item4', 'item5', 'item6'] };
for (i = 0; i < obj.items.length; i++) {
  var id = "check" + i;
  $('#checks').append('<input id="' + id + '" type="checkbox"><label for="' + id + '">' + obj.items[i] + '</label>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checks"> </div>

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

4 Comments

Thanks Dave but how can we bind the items to checkbox names?
sorry, I mean how about checkbox labels?
Thanks Dave, just one more question, in case of having array in js object?! which is for sure like item: [], how to handle that?
I wrapped the array in an object. Is this what you mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.