DINESH KUMAR
DINESH KUMAR

Reputation: 121

Need to remove value from html array

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.

Upvotes: 1

Views: 124

Answers (2)

tevemadar
tevemadar

Reputation: 13225

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)

Upvotes: 1

Noah
Noah

Reputation: 184

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

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

Upvotes: 0

Related Questions