Saving different data from selected item in JavaScript

I am having an issue with retrieving and saving data from my JS view to my controller and database. I can successfully retrieve the selected items' IDs using item_id.

However, when I enter quantities for the selected items, the quantity saved in the database is always the first quantity entered. For example:

Item: HpBook
Qty : 5

Item: Mac
Qty: 10

In the database, both items have a quantity of 5 instead of their respective quantities. What could be causing this issue?

JS

$('.form').append(
        '<div class="container"> '+
        '<input type="hidden" value='+item.id+' data-id="'+item.id+'" name="item_id[]" />'+  
        '<input type="text" class="quantity" placeholder=" Enter Value " name="quantity" />'+
        '<p class="total">Figures $:<span name="figures" id="figures"></span></p>'+
         '</div>'
);

Controller

 $item = new Item(array(
             'total' => $request->get('figures'),                    
         ));

 $item->save();
 $item->products()->attach($request->get('item_id'),['quantity' => $request->get('quantity')]);

Answer №1

Fix the spelling error in the quantity name field of your HTML:

'<input type="text" class="quantity" placeholder=" Enter Value " name="quantity[]" />'+

In your controller, start by creating an array for products and then link it to the model:

$products = [];
foreach($request->get('item_id') as $key => $id) {
    $products[$id] = ['quantity' => $request->get('quantity')[$key]];
}
$item->products()->attach($products);

Answer №2

The JavaScript code is missing the square brackets []

The correct syntax should be:

$('.form').append(
    '<div class="container"> ' +
    '<input type="hidden" value='+item.id+' data-id="'+item.id+'" name="item_id[]" />' +  
    '<input type="text" class="quantity" placeholder="Enter Value" name="quantity[]" />' +
    '<p class="total">Figures $: <span name="figures" id="figures"></span></p>' +
     '</div>'
);

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

Transferring information to the server with JSON in the Codeigniter framework

I have a JavaScript array (unitdata_set) that I need to send to the server for database processing using Codeigniter. JavaScript Array (unitdata_set):- [{"unit_id":"13","unit_title":"Testsdsdf","unit_max_occupancy":"3","unit_no":"1","unit_no_adults":"1", ...

Tone.js is failing to sync sequences during playback

I'm currently working on developing a sequencer using Tone.js. Right now, I have a basic sequence that plays when the user clicks the play button. However, I've encountered an issue where if the button is pressed to pause and then played again, t ...

Locate the immediate parent element and assign a class to it using jQuery

CSS: <div class="views-row views-row-10 views-row-even views-row-last"> <div class="sonuc"> <span>text1</span> </div> </div> <div class="views-row views-row-11 views-row-even views-row-last"> ...

"Implementation of clearInterval function may not always result in clearing the interval

The scrolling process within the div element flows smoothly in both directions, however, it seems to encounter an issue when executing the scrollBack() function. Despite including a clearInterval() statement at the intended point, the interval does not a ...

What is the best way to keep track of dynamically inserted input fields?

I've created a form with two text boxes: one for entering people's "name" and another for their "surname." By clicking on the page, you can add additional pairs of text boxes for both "name" and "surname," allowing users to input as many pairs as ...

JavaScript node_modules import issue

I've been grappling with this issue for quite some time now. The problem lies in the malfunctioning of imports, and I cannot seem to pinpoint the exact reason behind it. Let me provide you with a few instances: In my index.html file, which is complet ...

What iteration of the ECMAScript specification does the CEF platform accommodate?

Could you assist me in identifying the compatible version of ECMAScript in the chromium embedded framework (cef)? I am interested in utilizing ECMAScript 6 with it. ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

Obtain the registration ID for Android to enable push notifications by utilizing PushSharp

I am currently utilizing the PushSharp library and have come across deviceToken in the sample code provided on this link. Could someone kindly assist me on how to obtain this deviceToken? The PushSharp sample code does not clearly explain this. apnsBrok ...

Using a for loop in JAVASCRIPT to interact with MONGODB

I am running a MongoDB query to fetch data from the database, and the returned information looks like this: { _id: new ObjectId("623rf3f22275f399f88bb"), first_name: 'Are', last_name: 'You', email: '<a href="/c ...

Buttons and links with intricate geometries

I am currently developing a web application using Java/JSF and I am interested in finding out about technologies that would allow me to define intricate shapes as clickable buttons or links. Right now, my only option is to split an image into smaller trans ...

The onsubmit button is designed to function with only one specific function

When working with two JavaScript functions, only one error is being displayed instead of both. If I remove one function, the other works fine. But when both functions are present, only one error message is shown. Below is my JavaScript code: functi ...

Transferring information from a webpage to a popup using executeScript: A guide

I've successfully retrieved data from a website, but I'm struggling to send it to popup.js. I attempted to use executeScript with a callback, but it's not working for me. popup.js function getData() { chrome.tabs.query({active: true, c ...

Tips for utilizing tilesLoaded in Angular 8

Can anyone explain how to utilize the tilesLoaded feature in agm angular google map? I need to perform a specific action once the map is fully loaded. Does anyone have a demonstration of how to use tilesLoaded in angular (v8)? https://github.com/Sebastian ...

Embed the picture into the wall

I recently constructed a wall using three.js and would like to add an image similar to the one shown in the example below. Since I am still new to three.js, I am seeking assistance with placing the image. Can anyone provide guidance on how to do this? ...

Requirement for mobile browser support in creating object URLs - must use the URL prefixed as webkitURL."

After digging into the MDN web docs for createObjectURL (https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL), it's clear that when looking at Browser Compatibility (mobile), this method is specifically supported by certain mobile bro ...

"Why does adding a new span create space between it and the previous ones, and what can be done to prevent this from

Essentially, it creates the equation "a + b = c". However, I need to create "a + b = c" instead. HTML: <div class="container"> <span id="b__value">+b</span> <span id="c__value">=c</span> &l ...

Employ React Hooks for modifying the class names of elements and their related siblings

I have a function component in React hooks that I am working on. The goal is to change the className to 'active' when any element in the list is clicked, and remove the className from the other elements. const SideBar = () =>{ const [active ...

Steps for making a dropdown input field:1. Start by defining a

Is there a way to design a dropdown input using CSS or any other method? Take a look at this image for reference: Any suggestions on how to achieve it? ...

What is the process of transforming an xhr request into an angular $http request?

I've been successfully loading images using ajax with the following code. However, when trying to convert it into Angular and use $http, it's not working as expected. Original ajax code var xhr = new XMLHttpRequest(); xhr.open('GET', ...