0

I have

var updateActive = [{
    "id": "1",
    "name": "Koka Kola",
    "qty": "22",
    "price": "333",
    "active": "Yes"
}, {
    "id": "2",
    "name": "Pizza",
    "qty": "1",
    "price": "1",
    "active": "Yes"
}, {
    "id": "3",
    "name": "Jupi",
    "qty": "2",
    "price": "25000"
}, {
    "id": "4",
    "name": "Jupi",
    "qty": "333",
    "price": "333"
}]

var message = " ";

And array like that i can loop

$.each(updateActive, function (_, val) {
        val.id;
        val.name;
});

But i have problem how to put that values in loop in var message? like

<option value="val.id">val.name</option>

2 Answers 2

1

You can create DOM option elements in a loop and attach them to your dynamically created select like this:

var updateActive = [{
    "id": "1",
    "name": "Koka Kola",
    "qty": "22",
    "price": "333",
    "active": "Yes"
}, {
    "id": "2",
    "name": "Pizza",
    "qty": "1",
    "price": "1",
    "active": "Yes"
}, {
    "id": "3",
    "name": "Jupi",
    "qty": "2",
    "price": "25000"
}, {
    "id": "4",
    "name": "Jupi",
    "qty": "333",
    "price": "333"
}];
var message = "<select class='form-control' required name='article[]'></select>";
var select = $(message).get(0);
$.each(updateActive, function (_, val) {
  var option = document.createElement('option');
  option.id = val.id;
  option.innerHTML = val.name;
  select.appendChild(option);
});
alert(select.outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

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

Comments

0

jsBin demo

var message = "<select class='form-control' required name='article[]'></select>";
var $msg = $(message); // Convert to jQuery element 
var options = "";      // Create a String To concatenate HTML Option Elements

$.each(updateActive, function (idx, val) {
  options += '<option value="'+val.id+'">'+val.name+'</option>'; // Concat
});

$msg.html( options );  // Finally set String as Element's HTML


Without string concatenation you can directly .append() to Element:

jsBin demo

var message = "<select class='form-control' required name='article[]'></select>";
var $msg = $(message); // Convert to jQuery element

$.each(updateActive, function (idx, val) {  
  $msg.append('<option value="'+val.id+'">'+val.name+'</option>');
});

Comments

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.