I'm an experienced developer who is new to Jquery. I'm running into a problem where I have code that works when it chained together but not when it is separate and I would like to understand Jquery behavior.
I have a <div> with 4 buttons in it. When one of the 4 buttons is pressed, I need all 4 buttons to go away and a new button to replace it (the new button is a button with the same value as the one pressed but with different CSS to make it look different)
When the button is pressed I clear the <div> out like this
$(this).parent().empty();
I then build up the new button I want to insert
var splitstr = event.target.id.split('-');
var pick = splitstr[0];
var position_id = splitstr[1];
var singlebutton = '<button class="pick' + pick + ' pickbutton-box btn btn-primary btn-large madepick" name="pick" ' + 'id="made'+ position_id + '" ' + 'value="' + pick + '">' + pick + '</button>';
and then I tried to insert it back into the parent:
$(this).parent().append(singlebutton);
When I do this all 4 of the buttons in the <div> are removed but the new button is not added. However, if I build the string up before I do the empty and append
var singlebutton = " ---- HTML CODE for button ---- "
$(this).parent().empty().append(singlebutton);
Everything works as expected. This doesn't seem to make any sense to me. Can someone please explain what is happening.
You state you have something like this:
And an event handler like this:
When your handler code runs,
thispoints to the clicked button, which is removed by$(this).parent().empty();. You'd need to save a reference to the parent div to be able to reference it later, becausethiswill become empty. Something like this:The chained version works because a reference to the parent element is what is passed ahead starting from
.parent, and the value ofthisbecomes irrelevant.