I am generating row of input with arrays.
@foreach($msp_temp as $current)
<td>
<input type="number" step ="0.01" class="required" name="firstEntry[]" id="firstEntry">
</td>
<td>
<input type="number" step ="0.01" class="required" name="secondEntry[]" id="secondEntry">
</td>
...
I have a variable set somewhere like:
var entrysum = 0
I want to insert the variable value (entrysum) inside the [] and increase the variable every loop.
How do I insert entrysum value into firstEntry[], secondEntry[], and increase the variable value by 1 after every loop?
I will assume that as per code, there are always a couple of firstEntry and secondEntry and I understand that you want to update them together with the same value.
First, you get all the input numbers whose name starts with firstEntry and another for secondEntry:
var firstEntries = document.querySelectorAll('[name^="firstEntry"]');
var secondEntries = document.querySelectorAll('[name^="secondEntry"]');
Second, you iterate all elements and autoincrement the value.
for (var i = 0; i < firstEntries.length; i++) {
firstEntries[i].value = entrysum; // update firstEntry
secondEntries[i].value = entrysum; // update secondEntry
entrysum++; // increment entrysum
}
Note: if entrysum always starts in 0 and increments by 1, you can simply use i from the loop instead.
I hope this helps.
Try this
@foreach($msp_temp as $current)
<td>
<input type="number" step ="0.01" class="required" name="firstEntry[]" id="firstEntry">
</td>
<td>
<input type="number" step ="0.01" class="required" name="secondEntry[]" id="secondEntry">
</td>
@php
$entrysum++;
@endphp
Javascript is a client-side programming/scripting language. Looks like you are pasting elements from PHP, and entrysum
is a Javascript variable.
PHP is a server-side programming language. You cannot run Javascript before, or at the same time as PHP.
You can achieve your task by using a for
loop instead of foreach
, accessing the elements by index.
If you had this setup:
$msp_temp = [];
$i = 0;
for($i = 0; $i < count($msp_temp); $i++){
echo "<input type='number' step ='0.01' class='required' name='secondEntry[$i]' id='secondEntry'>";
// ...
}
echo "<script>var entrysum = $i;</script>"
The number will increase automatically, and the variable will be available for Javascript.
You are somewhat confused with []
array brackets is automatically increased next key,so
No need to to put extra effort to make array key
Rather you need to make input text id unique, to make unique id just add $key
like this
@foreach($msp_temp as $key=>$current)
<td>
<input type="number" step ="0.01" class="required" name="firstEntry[]" id="firstEntry{{$key}}">
</td>
Just submit you form and check post request you will get array of firstEntry
and secondEntry