php - javascript - Remove form element dynamically

66

I have a form in my PHP with JavaScript code to add select elements dynamically, which is working nicely :

<tr><th>Requester</th><td><input type="hidden" name="requester" value="<?php echo $_SESSION['user_id']; ?>"><?php echo $_SESSION['user_descr']; ?></td></tr>
<tr>
    <th>User(s) for whom you are requesting the access</th>
    <td>
        <div id="dynamicUsers">
                <?php
                   $q_users = 'SELECT id,descr,tnumber FROM users ORDER BY descr;';
                   $prep = $dbh->prepare($q_users);
                   $prep->execute();
                   $arrAll = $prep->fetchAll();
                   echo '<select name="firecallUsers[]">';
                   foreach($arrAll as $data)
                   {
                        echo '<option value="'.$data['id'].'">'.$data['descr'].'</option>';
                   }
                   echo '</select>';
                ?>
        </div>
        <input type="button" value="Add user" onClick="add_FC_User('dynamicUsers');">
    </td>
</tr>

The JavaScript is :

var counter = 1;
var limit = 5;
function add_FC_User(divName){
   if (counter == limit)  {
     alert("You have reached the limit of adding " + counter + " users");
   }
   else {
        var newdiv = document.createElement('div');
        newdiv.innerHTML = '<select name="firecallUsers[]"><?php
        $q_users = 'SELECT id,descr,tnumber FROM users ORDER BY descr;';
        $prep = $dbh->prepare($q_users);
        $prep->execute();
        $arrAll = $prep->fetchAll();
        foreach($arrAll as $data)
        {
            echo '<option value="'.$data['id'].'">'.$data['descr'].'</option>';
        }
        ?></select>';
        document.getElementById(divName).appendChild(newdiv);
        counter++;
   }
}

But I would like to add a little "remove" button next to each added element, for example something like this in the javascript :

?></select> <a href="#" onclick="remove_FC_User(''blabla'')"> remove </a>';

How can I script this javascript function in order to remove the dynamically-added elements ? I suppose I have to say something like (remove the child div created in parent div called dynamicUsers, but my child div doesn't have a name/id it seems)

any idea ? thanks!

PS : I tried this solution 1 (doesn't work) :

I tried to do something like :

1.adding a name to the div in the javascript, e.g :

var newdiv = document.createElement('div'); newdiv.id = "userDiv";

2.creating a function like :

function remove_FC_User(divName){ 
  var child = document.getElementById(userDiv); 
  var parent = document.getElementById(divName); 
  parent.removeChild(child); 
}

3.creating the remove link in the JS with :

?></select> <a href="#" onclick="remove_FC_User(\"dynamicUsers\")"> remove</a>';

but it won't work :(

576

Answer

Solution:

it's working nicely now with :

function randId() {
     return Math.random().toString(36).substr(2, 10);
}

            var counter = 1;
            var limit = 15;
            function add_FC_User(divName){
               if (counter == limit)  {
                 alert("You have reached the limit of adding " + counter + " users");
               }
               else {
                  var newdiv = document.createElement('div');
                  var randstring = randId();
                  newdiv.setAttribute("id", randstring);
                  newdiv.innerHTML = '<select name="firecallUsers[]"><?php
                  $q_users = 'SELECT id,descr,tnumber FROM users ORDER BY descr;';
                  $prep = $dbh->prepare($q_users);
                  $prep->execute();
                  $arrAll = $prep->fetchAll();
                  foreach($arrAll as $data)
                  {
                    echo '<option value="'.$data['id'].'">'.$data['descr'].'</option>';
                  }
                  ?></select> <a href="#" onclick="remove_FC_User(\'dynamicUsers\', \''+randstring+'\');"> remove</a>';
                  document.getElementById(divName).appendChild(newdiv);
                  counter++;
               }
            }

thanks a lot for your hints/help !

61

Answer

Solution:

mmh I managed to make it half-work with :

var newdiv = document.createElement('div');
newdiv.setAttribute("id", "one");

and

?></select> <a href="#" onclick="remove_FC_User(\'dynamicUsers\', \'one\');"> remove</a>';

and

function remove_FC_User(parentDiv, userDiv){
     var child = document.getElementById(userDiv);
     var parent = document.getElementById(parentDiv);
     parent.removeChild(child);
}

the elements get removed successfully, but it changes the remaining elements contents :( maybe I need to generate a random "id" and avoid using "one" for each ? how can I do that ? with a random function ? or a count ?

154

Answer

Solution:

You could set an id of your newly added element and then use it with your onclick:newdiv.setAttribute("id", "SOME_GENERATED_ID"); and then

 <a href="#" onclick="var elem =document.getElementById("SOME_GENERATED_ID"); elem.parentNode.removeChild(elem);">remove</a>;

Or you could use a class or name or data-* attribute. Or you could just remove the sibling of your "a" attribute etc.

People are also looking for solutions to the problem: php - Form loading external script after submiting

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.