Jump to content

how to add and remove button dynamically with javascript


Pawan_Agarwal

Recommended Posts

I have this array that has n elements ---> list_array = new Array(); it contains ['Product 1','Product 2','Product 3','Product 4','Product 5','Product 6','Product 7','Product 8']

 

what I am trying to do is that starting a loop from j=0 to j<n, I am adding button on html page, now when I click on button, it must remove itself from the page. I want to do this with the help of javascript...Is there anyone who can help ???

 

If I click on "product 8", the page must display other 7 buttons and it must delete the button itself on the page.....

 

function create()

{

 

  for(j=0;j<i;j++)

{
"<button onclick='remove_me(this)' id="+list_array[j]+">Remove</button><br>";
}
}

 

 

function remove_me(obj)

{

_button  = obj.id;

remove(_button);

}
 
 
I am trying to perform this operation, however, it only receive "Product" in obj.id.............It skips the text after the first whitespace.....
I hope that you got my concern, looking for quick reply.......
 
Link to comment
Share on other sites

First, the id can't have any spaces, so you should remove the spaces from the ids. To remove the element, you should use the parent and removeChild,

e.g. (your function example)

function remove_me(obj)
{
    obj.parentNode.removeChild(obj);
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.