0

How can I create an array from this table/form? The onclick function formData() from the dynamic table only returns a concatenated string. I need to create an associative array in JSON using the 'device' variable as key, however I'll settle for any sort of array at all. Clearly, I'm not very good at this...

function createInputTable() 
    {
    var num_rows = document.getElementById('rows').value;
    var tableName = document.getElementById('conn_input_device').value;
    var column_number = 2;
    var tdefine = '<form id="form"><table id="table" border = "1">\n';
    var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
    var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
    var tbody = '';
    var tfooter = '</table>';
    var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
    var i = 0;                  

    for (var i= 0; i < num_rows; i++)
      {
      tbody += '<tr><td>' + (i+1)  + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
      tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
      }
      document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
      
    }
    
    
    function formData()
    {
        var cellData = document.getElementById("form");
        //var device = document.getElementById('device').value;
        //var j;
        var obj = [];
        for(j=0; j< cellData.length; j++)
        {
            obj += cellData[j].value;
        }
        var json = JSON.stringify(obj);
        alert (json);
        //document.getElementById('result').innerHTML = json;
    }
    <form id="tableGen" name="table_gen">
        <label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
        <label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
        <input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
    </form>

    
    <div id="wrapper"></div>

4
  • what value you want to push into array? input column or output column? Commented Nov 23, 2018 at 10:19
  • Hi Jeswin, both input and output. Commented Nov 23, 2018 at 10:21
  • do you want the output like key value pairs? (eg: [ { 'Input' : 4,'Output' : '5'} , { 'Input' : 4,'Output' : '5'} ] Commented Nov 23, 2018 at 10:24
  • It's for an audio patch list - Something like [Main Console["InputOne", "Output One", "input Two", "output two".. etc]] , that way I can put that JSON into a db, then when it's return returned it can create another dynamic table to read the patch list. To be honest, I have no idea of the best way to do it, i'm just hacking away at it Commented Nov 23, 2018 at 10:30

2 Answers 2

2

1) This my answer how do this on VueJS and jQuery

2) Vanilla js - CODEPEN - DEMO

// Get DOM elements
const $el = [
    '#tmpl',
    '#user-count',
    '#people-count',
    '#form-items',
    '#btn-add',
    '#form',
].reduce((res, item) => {
    const method = item.startsWith('#')
        ? 'querySelector'
        : 'querySelectorAll'
    const key = item
        .replace(/\W/ig, ' ').trim()
        .replace(/\s+\w/g, v => v.trim().toUpperCase())
    res[key] = document[method](item)
    return res
}, {})

// Variable for dynamic template
const tmpl = $el.tmpl.innerHTML.trim()

// Click on Add new button
$el.btnAdd.addEventListener('click', () => {
    const peopleCount = +$el.peopleCount.value
    const html = Array(peopleCount)
            .fill(tmpl)
            .join('')
    $el.formItems.insertAdjacentHTML('beforeend', html)
})

// Submit form
$el.form.addEventListener('submit', e => {
    e.preventDefault()
    alert('Submit form by ajax or remove this method for default behavior')
})

// Add form click (it's need for dynamic handler on child elements)
$el.form.addEventListener('click', e => {
    // Delete behaviors
    if (e.target.classList.contains('btn-del') && confirm('Are you sure?')) {
        e.target.closest('.row').remove()
    }
})
<div id="app">
    <div>
        <div>
            <button id="btn-add">Add new user</button>
            <label>Number of People:</label>
            <input type="number" id="people-count" value="1" min="1">
        </div>
        <form id="form">
            <div id="form-items" data-empty="Users list is empty"></div>
            <button>Send</button>
        </form>
    </div>
</div>

<script type="text/x-template" id="tmpl">
    <div class="row">
        <label>
            Name:
            <input class="people" name="name[]">
        </label>
        <label>
            Surname:
            <input class="people" name="surname[]">
        </label>
        <label>
            Email:
            <input type="email" class="people" name="email[]">
        </label>
        <button class="btn-del">Delete</button>
    </div>
</script>

<style>
    .people {
        width: 80px;
    }
    #form-items:empty + button {
        display: none;
    }
    #form-items:empty:before {
        content: attr(data-empty);
        display: block;
    }
</style>

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

Comments

1

I have edited your code,

function createInputTable() 
    {
    var num_rows = document.getElementById('rows').value;
    var tableName = document.getElementById('conn_input_device').value;
    var column_number = 2;
    var tdefine = '<form id="form"><table id="table" border = "1">\n';
    var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
    var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
    var tbody = '';
    var tfooter = '</table>';
    var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
    var i = 0;                  

    for (var i= 0; i < num_rows; i++)
      {
      tbody += '<tr><td>' + (i+1)  + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
      tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
      }
      document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
      
    }
    
    
    function formData()
    {
        var cellData = document.getElementsByTagName("tr");
        var obj = [];
        for(var i=0;i<cellData.length-1;i++){
          obj.push(document.getElementById("i"+i).value);
          obj.push(document.getElementById("o"+i).value);
        }
        alert(JSON.stringify(obj));
       
    }
<form id="tableGen" name="table_gen">
        <label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
        <label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
        <input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
    </form>

    
    <div id="wrapper"></div>

2 Comments

THANK YOU Jeswin. I spent TWO DAYS trying to figure this one out. It really stumped me.
Done. Thanks again.

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.