Associate the name of the input field with an array where the values of the input field serve as

My input fields are as follows:

<input name='223' type='number' class='form-control score' value='70'>
<input name='224' type='number' class='form-control score' value='65'>
<input name='225' type='number' class='form-control score' value='87'>

I am looking to manipulate the 'name' attribute to serve as indices for each 'value' using JavaScript for ajax posting. Essentially, I aim to retrieve values as a single array and map the names as the array indexes.

For example:
array (
[223] => 70
[224] => 65
[225] => 87
)

Answer №1

One effective method is to utilize the reduce function to gather input values and names into an object, with the input name as the key and the input value as the value.

const result = [...document.querySelectorAll('input[type="number"]')].reduce((acc, i) => ({...acc, [i.name]: i.value}), {})

console.log(result)
<input name='223' type='number' class='form-control score' value='70'>
<input name='224' type='number' class='form-control score' value='65'>
<input name='225' type='number' class='form-control score' value='87'>

It's not recommended to assign keys in an array using random numbers as it deviates from the intended sequential nature of arrays starting from 0.

let array = [];

// Assigning a random index as a key for an array can lead to unexpected behavior.
// This action creates gaps in the array and is inefficient.
array["222"] = 222;

console.log(array)

This improper use of Arrays can result in memory leaks.

Answer №2

If you're looking to create an array of objects containing key-value pairs that correspond to the name and score attributes of each element, one approach is to utilize the array.map() method.

const inputs = Array.from(document.querySelectorAll(".score"))
const indexes = inputs.map(item => ({[item.name]: item.value}))
console.log(indexes)
<input name='223' type='number' class='form-control score' value='70'>
<input name='224' type='number' class='form-control score' value='65'>
<input name='225' type='number' class='form-control score' value='87'>

Answer №3

To achieve this, you have the option of using either an array or an object

If you opt for an array, be aware that it will result in multiple empty values as the name in your HTML begins with 223

var result = []
document.querySelectorAll('.score').forEach(item=>{
result[item.name] = item.value
})
console.log(result[223]) // 70
console.log(result[224]) // 65
// The resulting array will look like [,,,,,,,,,,,70,65,87]

The same outcome can be achieved using an object

var result1 = {}
document.querySelectorAll('.score').forEach(item=>{
result1[item.name] = item.value
})
console.log(result1[223]) // 70
console.log(result1[224]) // 65
// The resulting object (result1) will appear as {'223':70,'224':65,'225':87} 

Answer №4

Instead of utilizing an Array, I recommend using an Object since numeric indices in an Array can create a sparse and mostly empty, yet very large, Array.

Here is one possible approach:

// utility functions to streamline coding in larger projects;
// keeping a reference to the document:
const D = document,
  // a shorthand for querySelectorAll() that takes an Element as
  // a search context for the supplied selector,
  // defaulting to document:
  get = (sel, ctx = D) => ctx.querySelector(sel),
  // similar to above but a shorthand for querySelectorAll(),
  // converting the NodeList from querySelectorAll()
  // into an Array for Array methods:
  getAll = (sel, ctx = D) => [...ctx.querySelectorAll(sel)],
  // simple function to select elements matching a selector,
  // then iterate over the array of Element Nodes:
  collate = (sel) => getAll(sel).map(
  // using Arrow function with destructuring assignment to
  // retrieve 'name' and 'value' properties of Element,
  // passing them into the function body:
  ({
    name,
    value
  }) => {
    // creating and returning an Object with name variable
    // as property key and value property of element as value:
    return {
      [name]: value
    }
  }),
  // calling function on all <input> elements (change selector
  // for more specific control):
  nameAndValues = collate('input'),
// this could also be converted into JSON:
  nameAndValuesJSON = JSON.stringify(nameAndValues);
  
  console.log(nameAndValues);
  console.log(nameAndValuesJSON);
<input name='223' type='number' class='form-control score' value='70'>
<input name='224' type='number' class='form-control score' value='65'>
<input name='225' type='number' class='form-control score' value='87'>

JS Fiddle demo.

References:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on creating a Javascript leap year algorithm using Test-Driven Development techniques

Currently, I am working on crafting a leap year algorithm by utilizing a TDD suite. This marks my initial venture into the realm of TDD. Displayed below is the code extracted from the spec file. var Year = require('./leap'); describe('Lea ...

The product image does not display any other images

Hey, I'm experiencing an issue and need help replicating the photo changing effect on this website: I've managed to do everything right except for the photo changing feature (1 / 2 / 3 / 4)!! Here's what I have so far: Can anyone assist m ...

What is the best way to distinguish between errors when there are two forms on a single page using Laravel and jQuery?

I am encountering an issue with my login page where both the login and registration forms are present. Whenever there is a registration failure, the system automatically redirects me to the login form and errors appear in both forms simultaneously. I have ...

Ways to iterate through a JSON formatted array variable using JavaScript

Below is my code snippet, used to plot all the locations fetched from my database onto a Google map. $.ajax({ url:"http://localhost/church_finder/index.php/MapController/search_church", type:'POST', data: ...

Guide to retrieving IDs of images on a canvas during drag and drop functionality

I've developed a finite state machine drawing tool that includes drag-and-drop functionality for different images, such as states and arrows. Each arrow creates a div tag for the transition, with unique ids assigned to every state, arrow, and transiti ...

Utilizing a server for seamless communication between a mobile device and a website

Exploring a simple setup idea here: Imagine having a mobile app with a page that contains 4 lines of content (utilizing phonegap for development). The plan is to have a web page where data for those 4 lines can be inputted. Once the information is submitt ...

The Static Interface Binding in TypeScript

I have inquired about how to extend the static functionality of existing objects in JavaScript (using TypeScript). In all examples provided here, I am utilizing Object The code below showcases a polyfill definition for ECMAScript's Object.is function ...

Sliding content with the grace of a visual journey

I'm currently working on a content slider that is very similar to this one. My goal is to make it rotate automatically, but I've been struggling to get it to work. I've attempted various methods, including triggering a click event on the lin ...

Tips for transferring large data without a page redirect using jQuery's post method:

Seeking advice on how to send large data via jQuery POST without redirecting the page. I'm working on a mobile chat project where communication between user app and server is done using JSON. The issue arises when dealing with big data as the jsonGet ...

Ways to showcase information in a React dropdown menu

Having trouble creating a movie filter based on categories using React select? When trying to display the data, it just doesn't seem to work no matter what I do. Any advice or tips would be greatly appreciated as I'm new to React. The "categorie ...

Resetting the Countdown Clock: A Transformation Process

I have implemented a countdown timer script that I found online and made some adjustments to fit my website's needs. While the current setup effectively counts down to a specific date and time, I now require the timer to reset back to a 24-hour countd ...

Creating a popup using JavaScript in an ASP.NET page can be challenging when it comes to passing values

The list page in my parent window displays multiple rows, each representing an individual person. Next to each person's name is an icon that links to the "change status" page. When clicking on the icon, a popup page should open where the status of th ...

Guide to generating a multidimensional array from a single array in PHP

If we consider an array like this: array(1,2,3,4,...) I am in need of converting it to: array( 1=>array( 2=>array( 3=>array( 4=>array() ) ) ) ) Seeking assistance on this task. ...

Struggling with navigating the pop-up window in Webdriverio?

While conducting my testing with selenium and webdriverio, I encountered an issue when interacting with a pop-up PayPal window. Despite being able to switch to the pop-up successfully and confirming that a form element is enabled, I faced an error message ...

Selecting images using jQuery

Currently, I am in search of a jQuery image picker plugin that possesses the following features: Show a collection of images and enable the user to select one (and only one) by clicking on it If the user dislikes any of the pre-defined images, they shoul ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

Learn how to render list items individually in Vue.js using the 'track-by $index' directive

Recently, I switched from using v-show to display elements in an array one at a time in my Vue instance. In my HTML, I had this line: <li v-for="tweet in tweets" v-show="showing == $index">{{{ tweet }}}</li>". The root Vue instance was set up l ...

How can I remove a dynamically added <tr> element using jQuery?

I insert the <tr> into the <tbody> for (var i = 0 ;i < 12 ;i++){ $(`<tr><td>test</td></tr>`).appendTo('#songsTbody'); } within this HTML structure. <tbody id="songsTbody"> </tbody> ...

When a JSON stringified string contains a space-separated value, it can cause the data attribute to break

let dataObject = { "Cast_Code": "NA", "Mat_Code": "xxxx", "Pin_Num": "xxxx", "MatDetail": [ { "Batch_Number": "Patch PA", "Batch_Expiry": "No Expiry", "Batch_Quantity": "xxx", "Return_ ...

Is there a way to retrieve the positions of every occurrence of a specific substring within a given string?

Let's consider a scenario where we have the following string: $str = 'abc abc abc'; substr_count($str,'a') // returns 3 Would it be possible to generate an array that contains all the positions of occurrences for a specific subst ...