Retrieve value from array input

Is there a way to extract input text values from an array using JavaScript?

Here is the code snippet:

Item : <input id="t_item" name="t_item[]" type="text" class="teks3">
Cost : <input id="t_cost" name="t_cost[]" type="text" class="teks3">
<input type="button" id="tb_more_item" class="add_file"/>

Below is the corresponding JS code:

$("input#tb_more_item").click(function(){
   var new_file = $("
      Item : <input id='t_item' name='t_item[]' type='text' class='teks3'/>&nbsp;
      Cost : <input id='t_cost' name='t_cost[]' type='text' class='teks3'/>&nbsp;
   ");

   $("div#div_item").append(new_file).fadeIn();
});

I attempted to retrieve additional item values with the following code:

var item_value = [], cost_value = [];

$("input#t_item").each(function() {
   $thisItem = $(this);
   item_value = $thisItem.val();
});
$("input#t_cost").each(function() {
   $thisCost = $(this);
   cost_value = $thisCost.val();
});

alert(item_value +"-"+ cost_value );

However, the result only shows the last value entered in the input field.

Do you have any solutions to this issue?

Thank you.

Answer №1

Make sure your HTML is valid by avoiding duplicate IDs when adding elements. Consider using the name attribute in your .each() selectors instead.

Furthermore, be cautious when handling array variables inside the .each() functions. Avoid overwriting the array with the current item's value. Instead, ensure that each input value is added as a separate element in the array like so:

$('input[name="t_item\\[\\]"]').each(function() {
    item_value.push(this.value);
});

Similarly, apply this concept to t_cost as well.

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

Looping in jQuery: Tips for Improving Performance

In my popup window, I have a JavaScript function that utilizes jQuery to retrieve checked checkboxes from the parent window. It then uses jQuery again to access associated data from hidden fields in the parent window for each checkbox. var chked = $(&apos ...

Tips for Sharing Multiple Nested Arrays in AngularJS

I am working with an array in AngularJS, and here is an example: $scope.order.qty='20'; $scope.order.adress='Bekasi'; $scope.order.city='Bekasi'; To post this array, I use the following code: $http({ method : &ap ...

How to retrieve the current element in AngularJS version 1.x

I have done extensive research on how to get the current element in jQuery using $(this). However, I have not been able to find a similar method in AngularJS 1.x. Here is what I have tried: angular.element(this), but it does not work as expected. Below is ...

Remove any errors as soon as the input field becomes valid

My current setup involves AngularJS with node.js. To handle errors, I have devised the following strategy: node router effect.js: router.post('/', function(req, res, next){ req.checkBody('name', 'Eff ...

Showing JSON object in an Angular 2 template展示JSON对象在模

When I execute the following code: stanservice.categoryDetail(this.params.get('id')) .then((data) => { this.category = JSON.stringify(data.res.rows[0]); console.log(JSON.stringify(data.res.rows[0])); }) .catch((error) => { ...

Merging Two Angular Pages within a Jhipster Application

My jhipster application is simple, generating 2 entities: Product and Category. The generated pages to list the data for these entities can be found here. Specifically, there are pages for Product and Category. If I want to create a new page that combines ...

How can I use D3.js to form a circular group in an organization structure, link it with a circular image, and connect

Is it possible to create a radial grouped circle using d3.js, similar to the image below: https://i.sstatic.net/1Hwd2.jpg I have written some code as shown below. However, I am facing challenges in connecting every circle with a curved line and displayi ...

Tips for accessing the values of fields in React Material UI components

When I console log the object, it shows: { "week":undefined, "name":undefined, "code":undefined } Additionally, is it appropriate to wrap all Material UI components in a form tag and treat the entire code as a form? Here is ...

What is the best way to customize the functionality of the Done (node-dialog-ok) button in node-red when it is

I have created a custom node and I want to trigger some specific actions when the 'Done' button (with id: node-dialog-ok) in the editor-tray-toolbar is clicked, instead of its default functionality. Is it possible to override the onclick event o ...

Particles are not appearing when using the Three.js shader material

Hey there, I've been working on a simple scene with a grid of particles in the shape of a cube. Check it out here: https://codepen.io/sungaila/pen/qqVXKM The issue I'm facing is that when using a ShaderMaterial, the particles don't seem to ...

Defeat a JavaScript function or turn it into a Singleton Function

Is there a method to stop a running JavaScript function? Or is there a way to make sure that only one instance of the function runs at a time and any previous instances are removed upon restart? For example, if I call: _.defer(heavyDutyPaint); //How ca ...

Error: Unable to retrieve the name property of an undefined object within a React component that is being used as a child component within another parent component

FundraiserScreen.js // Import necessary components and dependencies; // Import Fundraiser component; const Children = ({ loading, error, fundraiserData }) => { if (loading) // Show skeleton loading HTML if (!error) return <Fundraiser fundraiser={fund ...

Using jQuery to retrieve the domain extension from a URL

Seeking assistance with extracting domain extensions from various URLs using jQuery. Uncertain how to account for all possible scenarios. Here are the parts of the URL that need to be extracted: https://www.amazon.**com**/dp/067144901X https://www.amazon. ...

How can you merge the class attribute with the ng-class directive based on boolean values?

In my custom directive's link function, I have the following code that dynamically generates a map using d3... map.append("g") .selectAll("path") .data(topojson.feature(counties, counties.objects.counties).features) .enter() .append("path") .attr("d" ...

Implement Javascript Event Listener

I'm a newcomer to the world of javascript and I’m struggling to understand why the code below isn't functioning correctly: var displayMessage = document.getElementById("notification"); displayMessage.addEventListener("click", function() { ...

Cart cannot function as a constructor

I'm currently learning express.js and trying to implement a shopping cart/session functionality into my project. Below is the code I have written so far, with a question at the end. Here is my cart.js: // Ensure that the file is required correctly b ...

The backend is not receiving the AJAX post, which utilizes dynamically-generated JSON

I'm relatively new to Bootstrap and frontend development in general. On a page I'm working on, there's a table that displays various configurations to the user. Each row has a Change button that triggers a modal popup when clicked. Here&apos ...

Jasmine spies falsely report the calling of functions when they have not actually been called

Below is the code snippet I am currently working with: $scope.deleteJob = function(job) { SandboxService.deleteJob(job.id).then(res => { if (res.status == 200) { ngToast.success(); $scope.refreshApps(); } ...

Troubleshooting issue with ng-change function in AngularJS

I have been working on developing a web application that includes two dropdown lists. My goal is to update the data in dropdown list 2 whenever there is a change in dropdown list 1. <tr> <td> State </td> <td> ...

Using jQuery to update the CSS background of a selected element among multiple elements sharing the same class

I am currently developing a basic jQuery script that will enable the background color of the clicked element to change. Below is the code I have so far: <dt> <input id="p_method_banktransfer" value="banktransfer" type="radio" name="payment[metho ...