Retrieving an array value by key from user input in HTML

<input type='number' name="productId" id="productId" value="5">
<input type="number" name="quantity[]" id="quantity">

In order to retrieve the quantity value, I utilized

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

The process functions smoothly to retrieve the desired value. Now, my objective is to designate productId as the key and the quantity values as numbers. The interface includes a submit button. Upon entering the product ID and quantity, the values will be added to an array. I aim to store these in a new array structured as follows:

var array = {
     2:10,
     3:5
};

Answer №1

When the window loads, a function called defineLogic is defined and assigned to the window.onload event. Inside the defineLogic function, an empty object named obj is created. Another function called createArray is defined within the defineLogic function. This function sets an onclick event listener on an element with the id "submit" and calls the createArray function when clicked.
 
The createArray function retrieves the values of two input elements with ids "productId" and "quantity" and stores them in the obj object. The obj object is then converted to a JSON string and logged to the console.

HTML input elements for productId, quantity, and a submit button are included in the code block.
<input type='number' name="productId" id="productId" value="5">
<input type="number" name="quantity[]" id="quantity">
<button id="submit">Submit button</button>

Answer №2

let items = [];
function addItem(){  
  let itemId = $('#itemId').val();
  let amount = $('#amount').val();
  let item = {};
  
  if(items.filter(i=>i[itemId]).length > 0){ 
      alert('The item ' + itemId + ' is already in the list');
      return false;
  }

  item[itemId] = amount; 
  items.push(item);
  
  console.log(items);
  return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form>
  <input type='number' name="itemId" id="itemId" value="5">
  <input type="number" name="amount[]" id="amount" value="10">
  <button onclick="return addItem()">Add item</button>
</form>

Answer №3

In order to retrieve the inputs, you will need a selector. If you are confident that the inputs are arranged correctly in the document and in pairs, you can use the following method:

function gatherData() {
  var inputElements = document.querySelectorAll('input');
  return {[inputElements[0].value] : inputElements[1].value};
};
<input type='text' name="productName" id="productName" value="Apple">
<input type='number' name="quantity[]" id="quantity" value="3">
<br>
<button onclick="console.log(gatherData())">Retrieve Data</button>

This function can easily be modified to generate an object from any number of input pairs.

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

Magnific Popup displaying only the initial item

As someone new to using jQuery and Magnific Popup, I am working on a grid of images. When an image is clicked, I want Magnific Popup to display a specific div containing information relevant to that particular image. <div class="grid"> <div c ...

Looking to remove a row with php, html, and ajax?

Trying to remove a row from an HTML table has been my latest challenge while working with Materialize CSS. Here is what I have so far, where the ID corresponds to the employee ID: https://i.stack.imgur.com/rjwba.png Below is the code snippet: <?php ...

When hosted, OpenCart encounters a JavaScript error stating that the property "document" cannot be read because it is null

After successfully running opencart on my local machine, I encountered some errors upon uploading it to the hosting/server. The specific error message is as follows: Uncaught TypeError: Cannot read property 'document' of null f.each.contents @ j ...

What could be the reason for my reset function not halting?

Why does my reset button keep clearing the canvas and emptying the chat box even though the return statement is supposed to end the function? Main.js var reset = function() { context.clearRect(0,0, canvas[0].width, canvas[0].height); context.be ...

Can you elaborate on this specific JavaScript concept?

I'm not very knowledgeable about javascript. Could someone please explain this structure to me? [{a:"asdfas"},{a:"ghdfh",i:54},{i:76,j:578}] What exactly is being declared in this structure? It appears to be an array with 3 elements, correct? Each e ...

Preserve the height of the previous div following an AJAX request

I am currently facing an issue where I have a script that utilizes ajax to receive a response containing a cart string (html code) with items from the cart. Inside the response handler, there is another script that sets the height of each div in the cart s ...

What could be causing my asynchronous JavaScript/Node.js function to bypass a significant portion of the code?

Upon calling the function below: async function sql_func(){ console.log('anothertest') async () => { console.log('third test') try { await sql.connect('heres the connection data') ...

How can I simply show a specific value from an object in Vue?

I've created a Vue application that filters messages and displays them on a page. Currently, when a user selects a message from the list, the entire JSON data associated with that message is shown on the page. However, I want to only display a specifi ...

How come the link function of my directive isn't being triggered?

I'm encountering a strange issue with this directive: hpDsat.directive('ngElementReady', [function() { return { restrict: "A", link: function($scope, $element, $attributes) { // put watche ...

You are unable to assign a string value instead of an object when making multiple selections

Utilizing react-select for autocomplete and option-related field has been quite helpful. However, I have noticed that in a single selection scenario, the code provided below only works when sending the value as a string. Unfortunately, it does not function ...

The entire Sphere Geometry in three.js is not completely encompassed by the texture

Click here to view the image I'm trying to create a rotating moon. Everything works perfectly with MeshStandardMaterial (with color but no texture), however, when I apply a texture to the sphere geometry, it behaves strangely. The issue I'm facin ...

How can I easily move from a shared page to a specific page in Angular 8?

Just stepping into the world of front-end development, I have a scenario where my menu page offers 3 options to navigate: Go to Arena. Go to Dungeon. Go to Battleground. However, clicking on any of these options leads me to a common page for character p ...

Jquery feature to automatically hide the submit button

Is there a way to automatically hide the submit button and display a message without requiring a mouse click? If the main balance is less than the inputted withdrawal amount, I want the submit button to be hidden automatically and a message stating insuff ...

Is it possible to activate events on select tags even when they have the disabled attribute?

All the select options on this page have been disabled with an ID that ends in _test, and everything seems to be functioning properly. However, I would like to display a title when the selects are disabled and the mouse hovers over them. The issue arises ...

When I submit 'name' through Postman, ValidatorExpress notifies me that the input for 'name' is missing

Whenever I use the 'POST' method in Postman with the URL http://localhost:7777/register, and select the options Body and row to paste the object {name: 'Martin}, why does it return "You must supply a name!" from the array ["You must supply a ...

The Katura video is loading properly, yet it is rotating instead of playing

I am working on a web application that involves playing videos from Kaltura platform and then loading the link on an iOS webview. <html> <body> <div id="myEmbedTarget" style="width:400px;height:330px;"></div> ...

Trigger Element Upon Click

Forgive me in advance for the lack of quality in this question, but I'll proceed anyway: All I want is for an element to slide open when clicked with a mouse! That's all! More specifically, I am looking for a single menu item that, upon clickin ...

Discover a suitable option or craft one using Mongoose

I'm facing a challenge with handling page ids in my code. The scenario is as follows: Page.findById(pageId).then(page => { const pageId = page.id; .. }); If no page id is provided, I need to select the first available page that meets certain ...

incorporating a dynamic parameter into the payload of an AJAX post request

I'm currently working on a function call where I want to extract the value of the variable data and place it in the data section of the function. However, despite my efforts, I haven't been successful so far. In PHP, I am attempting to retrieve t ...

Issue with transition delays on specific elements within a containing element

I'm currently developing an intro animation for a website, where the children are supposed to slide up from the bottom (margin-top: 80px). The container is set with a fixed height and overflow:hidden to create a smooth appearance. Each child has a tr ...