1

I have a form where I dynamicly add three fields at time.

Those fields each have diffrent class names.

I want to create a multidimensional array that stores the values of those fields.

The array needs to look like this:

var working_days = {
        0: {
            'workday': data,
            'from': data,
            'till': data
        },
        1: {
            'workday': data,
            'from': data,
            'till': data
        },
        2: {
            'workday': data,
            'from': data,
            'till': data
        },
        //etc.
    };

Prehaps using array push?

This is the code I have so far:

$('body').on('click','.createItem', function() {
    var working_days = {}

    console.log(values);
    $('input.startTime').each(function() {
        var startTime = $(this).val();
    });

    $('input.endTime').each(function() {
        var endTime = $(this).val();
    });

    $('select.day').each(function() {
        var day = $(this).val();
    });

});

What are possible ways to do this?

1 Answer 1

1

The jQuery helper function .serializeArray() could be a good starting point for you. The resulting array of objects then needs to be transformed into your required format, using .reduce(). Here is a little fiddle to demonstrate a possible solution:

const names={startTime:"from",endTime:"till"};
function addTimes(tblsel){
 $(tblsel).append($("#timegrp").html()) 
}
for (let n=6;n--;) addTimes("#times table");
$("#times").on("click",".rmv",function(){this.closest("tr").remove()});
$("#add").click(ev=>addTimes("#times table"));
$("#chk").click(ev=>{
  const res=$("#times").serializeArray().reduce((a,e)=>{
    if (e.name=="day") a.push({workday:e.value});
    else names[e.name] && (a[a.length-1][names[e.name]]=e.value);
    return a;
  },[]);
  console.log(res);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">add workday</button>
<button id="chk">check times</button>
<form id="times">
<table></table>
</form>

<template id="timegrp">
<tr><td><select name="day"><option>Monday</option>
<option>Tuesday</option>
<option>Wednesday</option>
<option>Thursday</option>
<option>Friday</option>
<option>Saturday</option>
<option>Sunday</option></select></td>
<td><input type="time" name="startTime" value="08:30"></td>
<td><input type="time" name="endTime" value="17:00"></td>
<td class="rmv" title="remove">&#x2718;<td></tr>
</template>

( My script creates an array of objects. The result as you requested it in your question was an object, not an array. )

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

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.