I am trying to create table with button in each row and when button is clicked new row is created between current and subsequent row. If any other button is pressed, previously created row is deleted and new one is created on new proper location. And so on, and so on. My approach is to use if-statement that would check if whichever button was pressed for the first time, if so, create row on proper location and save it's position to currPos. On the second and each subsequent click, first thing is to delete previously created row and create new in proper location and save newly created row position to currPos(in order to third click and each subsequent would know which one to delete).
The problem is that 'if (first==true)' is never executed, that's why error demands declaring currPos at the beginning of the script, so I created it with value = -1, so when whichever button is pressed last row is deleted, and then whole code is working as I want.
How can I fix my if-statement in order not to declare currPos at the beginning of the script, so that it's declaring in 'if(first==true)'?
/* Additionaly variable $firstPHP is created to connect onclick and specialFunc that there are two parameters, but the in PHP it's not even used - it knows that has to have two parameters because JS will use it(create it's own actually) later. Is that good approach? Can I inform onclick button that JS needs only rowID from php and second parameter is created within JS function? */
<?php
$firstPHP = true;
$provider = "Test_provider";
echo '<table id="my-table">';
for($counter = 0; $counter <= 5; $counter++){
$rowID=$counter+1;
echo' <tr id ="'.$counter.'"><td><button onclick="specialFunc('.$firstPHP.',\''.$rowID.'\')">'.$provider.'</button></td><td>Row '.$counter.' Col '.$counter.'</td><td>Row '.$counter.' Col '.$counter.'</td><td></td><td></td></tr>';
}
echo '</table>';
?>
<script>
var currPos= -1;
function specialFunc(first = true, test){
if (first == true){
function addRow(test) {
var currPos = test;
let tableRef = document.getElementById("my-table");
let newRow = tableRef.insertRow(test);
let newCell = newRow.insertCell(0);
newCell.colSpan = 5;
let newText = document.createTextNode('New bottom row1');
newCell.appendChild(newText);
first = false;
}
}
document.getElementById("my-table").deleteRow(currPos);
let tableRef = document.getElementById("my-table");
let newRow = tableRef.insertRow(test);
let newCell = newRow.insertCell(0);
newCell.colSpan = 5;
let newText = document.createTextNode('New bottom row2');
newCell.appendChild(newText);
currPos = test;
}
Aucun commentaire:
Enregistrer un commentaire