0

In a HTML form I have a check box like-

<select class="text" name="department" id="department">
    <option value="">Select department</option>
    <option value="a">A</option>
    <option value="b">B</option>
    <option value="c">C</option>
 </select>

Now, I wish to give user capability to add or delete departments in the list. He/She may add branched D and E or may delete branch B.

I wrote a Javascript function to list all the branch names as checkboxes to choose the elements to delete-

function deletefield() {
    var container = document.getElementById('drop_down');
    container.innerHTML="";
    for(i=0; i<passed_array.length; i++) {
        var check = document.createElement("INPUT");
        var br = document.createElement("BR");
        check.setAttribute("type","checkbox");
        check.setAttribute("value",passed_array[i]);
        var label = document.createElement('label');
        label.htmlFor = "id";
        label.appendChild(document.createTextNode(passed_array[i]));
        container.appendChild(check);   
        container.appendChild(label);
        container.appendChild(br);
    }
}

But I have no idea how to proceed it forward to delete the selected branches.

On surfing Internet I came across this code

function remove(id) {
    return (elem=document.getElementById(id)).parentNode.removeChild(elem);
}

I don't know if it can help with dropdown or not. Could someone help me decide which is the better approach and how should I proceed with it?

Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40

2 Answers2

2

Yoy may select the specific option you want to delete. Using jQuery would be as follows

var removeChild = function(branchToDelete) {
    $("option[value='"+branchToDelete+"']").remove();
}

To add new options to the dropdown menu you must append the new options to the dropdown menu

var addChild = function(newBranch) {
    $("#department").append("<option value='"+newBranch+"'>"+newBranch+"</option>");
}

See also Select2Js Plugin. It has plenty of good funcionalities related to dropdown menus that could be useful for you

Juan Rivillas
  • 897
  • 2
  • 9
  • 23
0

HTML:

<a id="add">Add More</a>

JavaScript:

var i = 1;
$("#add").click(function(){
                var appendFields = '<tr>';
                appendFields += '<td><select id="dropdown_'+i+'" name="dropdown_name[]"><option value="1">One</option></select></td>';
                appendFields += '<td><a style="color: red; cursor: pointer;" class="remCF">Remove</a></td>';
                appendFields += '</tr>';
                $("#table_id").append(appendFields);
                i++;
            });
            $("#table_id").on('click','.remCF',function(){
                $(this).parent().parent().remove();
            });

        });
Waqas Shahid
  • 1,051
  • 1
  • 7
  • 22