简体   繁体   中英

JS associative array from form input field

My form contains multiple input fields. For example:

<input type="number" class="attribute-class form-control"  id="Size" min="1" max="99999" name="attribute[]">
<input type="number" class="attribute-class form-control"  id="weight" min="1" max="99999" name="attribute[]">

Now I want to create an array, something like this array[size => 10, weight=> 20]

Is that even possible? So far I used this function I found on another topic, but I get a regular array with just the fields value.

var attribute = $("input[name='attribute[]']").map(function(){
            return $(this).val();}).get(); 

Reason for this: I have to load additional input fields in my form with ajax, depending on what type of product the user selects, and then I have to store fields name and value in database. This is the only option I could think of.

You need to create an object, not an array. You want to use the IDs as the property names in the object.

 $("#x").click(function() { var attribute = {}; $("input[name='attribute[]']").each((i, input) => attribute[input.id.toLowerCase()] = input.value); console.log(JSON.stringify(attribute)); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Size: <input type="number" class="attribute-class form-control" id="Size" min="1" max="99999" name="attribute[]"><br> Weight: <input type="number" class="attribute-class form-control" id="weight" min="1" max="99999" name="attribute[]"> <br> <button id="x">Click</button> 

It seems like you want to create an object to store the values from your input fields,

Maybe try something like this :

    var myObject = {};
    document.querySelectorAll("input[name='attribute[]']").forEach(element => {
       myObject[element.id] = element.value
    });
    console.log(myObject); // <-- this should have your values in it now.

JavaScript does not have associative arrays, use a JavaScript object which is very similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM