1

I have used array to get the input values of each row in html. The code is

<input type="text" name="source[]" id="source'+row'">

I need to remove the elements from the array when i remove the a row.

var source=document.getElementsByName("source");
 Array.prototype.forEach.call( source, function( node,index ) {
    if(index==id){
        node.parentNode.removeChild( node );
    }
});

when I console the result, the child is removed. But when I submit the form using PHP, the array has empty values.

`['24','','',56]`

How to remove the empty values.

4
  • I don't fully understand your problem but a quick fix would be to filter the array by its elements value before you send them. E.g.: source.filter(item => item); This will remove empty values. Commented Jan 24, 2018 at 17:13
  • Is var source and array? Where is id coming from? Is the only thing wrong that the source array is not correct? It would help if you posted more of your code so that we can gain context Commented Jan 24, 2018 at 17:24
  • If the input is a child node of the row, and you remove the row using removeChild or similar, it will get rid of the input automatically. Commented Jan 24, 2018 at 17:31
  • Thanks for your ideas, I fixed the issues in php file Commented Jan 26, 2018 at 17:26

2 Answers 2

1

It just works, check again what you are doing.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script>
            function test(){
                var source=document.getElementsByName("source[]");
                Array.prototype.forEach.call( source, function( node,index ) {
                    if(index===1){
                        node.parentNode.removeChild( node );
                    }
                });
            }
        </script>
    </head>
    <body>
        <?php
        var_dump($_GET);
        ?>
        <hr>
        <form action="index.php">
            <input type="text" name="source[]"><br>
            <input type="text" name="source[]"><br>
            <input type="text" name="source[]"><br>
            <input type="text" name="source[]"><br>
            <input type="submit" value="sub">
        </form>
        <button onclick="test()">test</button>
    </body>
</html>

(It is a PHP file expecting to be index.php, sending the array to itself, button test removes element with index==1)

Sign up to request clarification or add additional context in comments.

Comments

0

An easy way to remove empty values from an array would be:

var this_array = this_array.filter(function(x){
  return (x !== (undefined || null || ''));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.