0

I am trying to delete select box using jQuery remove function but it does not work. The select box itself is dynamically generated one. I want to delete the same select box if the user wants to delete the dropdown after adding. My code is:

    $("#dltElement").click(function() {
        $("#idSelect").remove();   
    });

My code to add the select boxes:

$(document).ready(function() {
    var count = 3;
    $("#btnCompare").click(function() {
        if (count > 4) {
            alert("Only 4 options are allowed");
            return false;
        }
        $("#form-group").append(
            "<select name='idSelect" + count + "' id='idSelect" + count + "'>" +
            "<option>--Select Product" + counter + "--</option>" +
            '<option value="p1">Product 1</option>' +
            '<option value="p2">Product 2</option>' +
            "</select>" + '<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" />'
        );
        count++;
    }); // Script for adding dropdown dynamically

});
3
  • idSelect is not present you have to use idSelect0 or idSelect1 or use event delegation to delete the closest element select Commented Sep 21, 2015 at 11:52
  • Yes I am using the selector referring to its respective select box. For example $("#dltElement3").click(function() { $("#p3").remove(); }); in my case. Commented Sep 21, 2015 at 12:38
  • check my answer below. Shouldn't be repeating call listeners, rather use one Commented Sep 21, 2015 at 12:40

3 Answers 3

3

#idSelect is not present you have to use #idSelect0 or #idSelect1 ... and so on. Rather than you can lookup the events using event delegation on your #form-group to delete the closest element select closest to your input button or in your case your sibling select. This ~ is a sibling selector and will select the sibling select.

A good idea would be to add a class to your select and use that instead as we have used your class .btn-minus for listening to click events, (in case if you have more than one select all will be selected)

$("form-group").on('click', '.btn-minus' , function() {
     $(this).find('~select').remove();   
});

Find the sibling select and remove

Edit 2

I have added a snippet using .closest() You can check it out. Closest will try to locate the parent div with class container and remove the select and the minus button

$(document).ready(function() {
    
    $("#form-group").on('click', '.btn-minus' , function() {
       $(this).closest('.container').remove();   
    });
    $("#btnCompare").click(function() {
        var count = $("#form-group > div.container").length;
        if (count >= 4) {
            alert("Only 4 options are allowed");
            return false;
        }
        //you need to have data-id="number" for all div.container, add class container and data-id to all the divs having select and button
        var label = $("#form-group > div.container").last().data('id')*1+1;
        $("#form-group").append(
            "<div class=container data-id="+label+"><select name='idSelect" + label + "' id='idSelect" + label + "'>" +
            "<option>--Select Product" + label + "--</option>" +
            '<option value="p1">Product 1</option>' +
            '<option value="p2">Product 2</option>' +
            "</select>" + ' <input type="button" value=" - " id="dltElement' + label + '" class="btn-minus pull-left" /></div>'
        );
        
    }); // Script for adding dropdown dynamically

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="form-group">
  <input type=button id=btnCompare value=btnCompare />
  <div class="container" data-id="1">
    <select id="idSelect1" name="idSelect1">
      <option>--Select Product1--</option>
      <option value="p1">Product 1</option>
      <option value="p2">Product 2</option>
    </select>
    <input disabled type="button" class="btn-minus pull-left" id="dltElement1" value=" - ">
  </div>
  
  <div class="container" data-id="2">
    <select id="idSelect2" name="idSelect2">
      <option>--Select Product2--</option>
      <option value="p1">Product 1</option>
      <option value="p2">Product 2</option>
    </select>
    <input disabled type="button" class="btn-minus pull-left" id="dltElement2" value=" - ">
  </div>
</div>

Edit 3:

Please find updated snippet. you need to have data-id="number" for all div.container, add class container and data-id to all the divs having select and button.

It is hard to have what you want since you can delete from the middle as well. You can have an array of deleted objects and update it everytime you delete or add into that. In this code I have added to disbaled input delete for 1 and 2 so that you can add and delete other 2. You can play around the logic.

It counts the number of divs in DOM and then checks if you are trying to add more than the limit, It then picks the last added in DOM and increments the data-id to use it as a label for the next select

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

3 Comments

It does not remove the closest select element. I checked the console but no error seems to appear.
This works great. But now the problem occurs if I already added two more select boxes and deleted them, try to add more select options further it shows the message for alert("Only 4 options are allowed"); As I want only two more select options to be created after the default drop-downs placed. For the time being if I remove the counter it starts adding the elements but I wanted to set the limit.
Ultimate solution. It worked exactly the way I wanted it to be. Thank a lot!!
2

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).

i.e.

$(document).on('event','selector',callback_function)

Example

As you have defined CSS class, use the to get the select element and perform removal operation.

$("#form-group").on('click', ".btn-minus", function(){
    $(this).prev('select').remove();
});

$.fn.prev()

Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

Comments

1

you are assigning the <select> element an id that ends with a number, like this :

<select name='idSelect"+count+"' id='idSelect"+count+"'>

this means you end up with something like this :

<select name="idSelect1" id="idSelect1">
...
</select>

so the selector $("#idSelect") will never hit it unless it includes that number.

The part where you add the button :

'<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" />

has that same problem.

An easy way (though arguably not the best way) to achieve what you want is this :

function removeSelect(evt)
{
   var selectBox = $(evt.currentTarget).parents(".group").find("select");
   //do with select box as you will
}

$(document).ready(function() {
    var count = 3;
    $("#btnCompare").click(function() {
        if (count > 4) {
            alert("Only 4 options are allowed");
            return false;
        }
        $("#form-group").append(
            "<div class='group'>
            "<select name='idSelect" + count + "' id='idSelect" + count + "'>" +
            "<option>--Select Product" + counter + "--</option>" +
            '<option value="p1">Product 1</option>' +
            '<option value="p2">Product 2</option>' +
            "</select>" + '<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" onclick="removeSelect(event)" /> </div>'
        );
        count++;
    }); // Script for adding dropdown dynamically

});

3 Comments

Please don't recommend ugly inline click handler
i'm not recommending it. in fact i'm saying it's arguably not the best way.
@TimothyGroote On the click event of btnCompare the Select box and minus button are generated with respective IDs. So the delete event code actually takes the dynamic ID itself. I am sorry for editing the code for delete event before I posted the question.

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.