I have asked this question one time but couldn't get any proper answer.So making the question simpler.Im using codeigniter
javascript function in view file here the abc output looks like this
0:{a:'1',b:'2',c:'35'}
1:{a:'2',b:'3',c:'34'}
2:{a:'5',b:'1',c:'87'}
3:{a:'4',b:'3',c:'90'}
function test()
{
const show_div = document.getElementById('div_show');
const abc =[];
abc.push({a,b,c});
for (const data of abc){
const values = Object.values(data);
for (const value of values){
const input = document.createElement(
'<input type="text" name="a[]" value=" '+ value[0]+ ' " required>' +
'<input type="text" name="b[]" value=" '+ value[1]+ ' " required>' +
'<input type="text" name="c[]" value=" '+ value[2] + ' " required>'
);
input.innerText = value ;
show_div .appendChild(
input
);
}
}
}
I need to get this to the view
<form>
//there are more divs here
<div id='div_show'>
//need output like this
// 1 2 35
// 2 3 34
// 5 1 87
// 4 3 90
</div>
</form>
And then I want to pass a,b,c data to model How can I get this data.Actually im creating this view output just pass the data in post method because in form submit its passing the data through action url without ajax.
You can try like this. You can add any input field with the array of object data. I have separated each array item with a div so that you can design it with css or you can remove it if you don't need the div.
const data = [{a:'1',b:'2',c:'35'},
{a:'2',b:'3',c:'34'},
{a:'5',b:'1',c:'87'},
{a:'4',b:'3',c:'90'}];
function show() {
const container = document.getElementById("div_show");
let fields = '';
for(item of data) {
fields += '<div class="field_row">';
Object.keys(item).forEach( key => {
fields += `<input type="text" name="${key}[]" value="${item[key]}" required>`
})
fields += '</div>';
}
container.innerHTML = fields;
}
show()
<form><div id="div_show"></div></form>
Kind of ES6 way
const data = [{a:'1',b:'2',c:'35'},{a:'2',b:'3',c:'34'},{a:'5',b:'1',c:'87'},{a:'4',b:'3',c:'90'}];
function show() {
const fields = data.map((obj) => {
const row = Object.entries(obj)
.map(([key, value]) =>`<input type="text" name="${key}-${value}" value="${value}">`)
.join('');
return `<div>${row}</div>`;
}).join('');
document.getElementById("div_show").innerHTML = fields;
}
show();
<form><div id="div_show"></div></form>
Can you please provide more specific details your exact output?
If you need just 3 input elements in side that div(#div_show)
, your inner loop is redundant, you can eliminate it and it would give you what you need.