0

I am attempting to call the remove() jQuery function on a div tag which has been added after the page is loaded. I am adding this div link this:

$(probablyHide).html(addedDiv);
<div class=probablyHide>
 <div onClick="myMethod(this)" class="hide" id="1">i want to hide this div 1</div>
 <div onClick="myMethod(this)" class="hide" id="2">i want to hide this div 2</div>
 <div onClick="myMethod(this)" class="hide" id="3">i want to hide this div 3</div>
</div>

However for some reason my remove() is not working properly.

function myMethod(div)
{
    var button = $(div).closest('div.otherDiv').find("select[id^='stuff']");    
    button.val(div.id); 
    $(div).remove();
    $(button).trigger('change');
};

What is weird is if I edit out the following lines in my function. The div will be deleted.

  button.val(div.id); 
    $(button).trigger('change');
KiaMorot
  • 1,668
  • 11
  • 22
user2524908
  • 861
  • 4
  • 18
  • 46
  • 1
    @DanyCaissy - He's assigning it with `onClick="myMethod(this)"`, so he can't do that. `div` is the raw HTML element. – Justin Morgan - On strike Jul 18 '13 at 14:49
  • 1
    I'm not sure why people hate this question so much. I've seen far worse on SO. – Justin Morgan - On strike Jul 18 '13 at 15:32
  • 1
    @JustinMorgan Absolutely. It's especially annoying when downvoters don't explain why they've done it. How does that benefit the community? And I quote from StackOverflow documentation: 'Down-voting should be reserved for extreme cases. It's not meant as a substitute for communication and editing.' – Holf Jul 18 '13 at 18:57

3 Answers3

4

Use jQuery event handlers if you are going to use jQuery:

$(document).on('click', '.hide', function(){
    var $div = $(this);
    var button= $div.closest('div.otherDiv').find("select[id^='stuff']"); 
    button.val(this.id); 
    $div.remove();
    $(button).trigger('change');
});

Also please try not to use numeric IDs for elements.

Naftali
  • 144,921
  • 39
  • 244
  • 303
  • 6
    **Short note here** *(although I'm on your side)*: IDs beginning with numbers are now [valid in HTML5](http://www.w3.org/TR/html-markup/global-attributes.html#common.attrs.id). – Jeff Noel Jul 18 '13 at 14:48
  • I dont know if I can use the jquery event handlers. Because the div is added to the page dynamically. However I will give it a shot. I am very new to jquery so eveything I say is probably wrong to some extent... – user2524908 Jul 18 '13 at 14:49
  • 1
    @JeffNoel IDs beginning with numbers do still cause issues with CSS, however. Although there is a workaround for that: http://stackoverflow.com/questions/16500748/css3-notselector-isnt-working-on-section/16500823#16500823 – Holf Jul 18 '13 at 14:52
  • This isn't the problem, and unobtrusive JavaScript isn't the only correct solution. It's completely possible to make this work with plain DOM event handling: http://jsfiddle.net/xWATj/ – Justin Morgan - On strike Jul 18 '13 at 14:58
  • @JustinMorgan read the OP -- the objects were added dynamically – Naftali Jul 18 '13 at 14:59
  • Do I have to attach that method to my div? It doesnt seem to be invoked when I click on the div. The div is created on the page after the document is loaded – user2524908 Jul 18 '13 at 14:59
  • @Neal - That doesn't matter. He's attaching the handler with their `onClick` attribute. Works fine: http://jsfiddle.net/hh5pt/ – Justin Morgan - On strike Jul 18 '13 at 15:06
  • 1
    @JustinMorgan inline is ugly.... also he is using jQuery! might as well **use jQuery**! – Naftali Jul 18 '13 at 15:07
  • I agree, inline is ugly. But it's still correct. Not using jQuery isn't the problem here. – Justin Morgan - On strike Jul 18 '13 at 15:19
  • If I call myMethod(this) inline the method is invoked and nothing will happen. However if I click the div a second time it will be deleted. – user2524908 Jul 18 '13 at 15:38
1

It's probably not working as you have the JavaScript loading with onLoad.

Simple fix would be to use jQuery event handlers

Demo: enter link description here

//$('.probablyHide').html(addedDiv);
//Use the following:
addDiv($('.probablyHide'), addedDiv);


function myMethod(div){

    var button= $(div).closest('div.otherDiv').find("select[id^='stuff']");
    button.val(div.id); 
    $(div).remove();
    $(button).trigger('change');
}

function addDiv(container, element) {
    container.append(element);
    element.click(function() {
          myMethod(this);  
    });
}

$('.probablyHide .hide').each(function() {
    $(this).click(function() {
          myMethod(this);  
    });
})

Fixed HTML:

<div class="probablyHide">
    <div class="hide" id="1"> i want to hide this div 1 </div>
    <div class="hide" id="2"> i want to hide this div 2 </div>
    <div class="hide" id="3"> i want to hide this div 3</div>
</div>
Steven10172
  • 2,003
  • 4
  • 21
  • 37
  • I think I may have to use an inline method call. I tested similar code to the above in jsfidle before and it successfully removed the div. However when it is implemented into my page it does not work. does $('.mstrListBlockMessage .sumElm').each(function() { $(this).click(function() { myMethod(this); }); }); need to be included in the $(document).ready()? – user2524908 Jul 18 '13 at 15:08
  • @user2524908, I would try putting it in $document.ready() or just $(function(){ /*code*/ }); and see if it works that way as you want the DOM to be there in order to attach an event to it – Steven10172 Jul 18 '13 at 15:12
0

Your code is fine. Proof: http://jsfiddle.net/uQ9Xz/

There are only three things you need to make sure of:

  1. Your handler (myMethod) needs to exist when the divs are born. The best way to do that is to put it in the head, and make sure you're not creating it after document.load or anything like that.

  2. jQuery's .closest() method looks for something containing the current element. So there needs to be a div with class="otherDiv", and it needs to contain both your probablyHide div and a button whose ID starts with "stuff". Your DOM may have the wrong structure.

  3. Is button supposed to be a button or a dropdown list? You're treating it like a button, but your code is looking for select[id^='stuff'].

So just fix the selector and put your code in the <head>:

<script type="text/javascript">
   function myMethod(div) {    
      var button = $(div)
                      .closest('div.otherDiv')
                      .find("button[id^='stuff']"); //note the different selector

      //etc..
   }
</script>

Inside the <body>:

<div class="otherDiv">
    <button id="stuff">stuff</button>

    <div class="probablyHide">
        <div onClick="myMethod(this)" class="hide" id="1"> i want to hide this div 1 </div>
        <div onClick="myMethod(this)" class="hide" id="2"> i want to hide this div 2 </div>
        <div onClick="myMethod(this)" class="hide" id="3"> i want to hide this div 3</div>
    </div>
</div>
Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
  • hm, all of the ways in which I write this code function in jsfiddle however they seem to break when I add to my page. I am integrating this into a page with a good deal of existing javascript. I dont think the problem is with getting any of the html elements as performing $(elm).html() will output the proper div and or button which I am performing an action on. The page doesnt seem to load if I add the method inside of the $(document).ready(function). I appreciate all the suggestions – user2524908 Jul 18 '13 at 15:29
  • If I call myMethod(this) inline the method is invoked and nothing will happen. However if I click the div a second time it will be deleted. – user2524908 Jul 18 '13 at 15:38
  • @user2524908 - You must have something else going on in your page, outside the code we can see. Have you checked the jsFiddle example I posted? – Justin Morgan - On strike Jul 18 '13 at 16:18
  • Yeah that example works and I implemented something very similar, and then used your same example and it didnt work on my page:(. I have another button on the page which is adding the divs which I am attempting to remove. It is being done with $(sumDiv).append(tmpText); where tmpText =
    i want to hide this div 1
    Whats really weird is if I click the div a second time it is removed...
    – user2524908 Jul 18 '13 at 16:21
  • Without seeing your code, I can't say for sure what's wrong. Just put alerts or something into the page so you know the function is running, and keep the browser console open to tell you if there are any JavaScript errors. – Justin Morgan - On strike Jul 18 '13 at 16:28
  • No javascript errors and the functions are being hit at the correct times. Ill admit Im very new to jquery/js. The application I am integrating this into is fairly complicated and obviously something is breaking it. Are there any other ways to remove divs from the page? Maybe using dom? – user2524908 Jul 18 '13 at 16:31
  • donno why but initial tests show this works... $("#" + div.id).remove() – user2524908 Jul 18 '13 at 16:43
  • If `div` is a DOM object, there's no reason that would work when `$(div).remove()` doesn't. Either that's a mistake, or `div` isn't what you think it is, or jQuery isn't set up right in your application. – Justin Morgan - On strike Jul 18 '13 at 19:01