Link to home
Start Free TrialLog in
Avatar of brad0525
brad0525

asked on

remove current contents of div and then add new content using DOM

I am using the code below to move items to the "second" div..It works fine to move them. I know need it to move the new item to the "second" div but remove the current item too. Any help would be greatly appreciated..thanks
<script language="javascript">
	$(document).ready(function() {
		$("a").click(function() {
			$(this).parent().remove("#second");
			$(this).parent().appendTo("#second");
			$("<input/>").attr({
				id: $(this).attr("value"),
				style: "border:none;font-weight:bold;background-color:white;",
				value : "I'm "+$(this).attr("value")
			}).appendTo("#second");
		});
	});
</script>


First section :<br />
<div id="first">
    <div><input type="hidden" id="chip1"  value="1" >Chip1&nbsp;<a href="#" value="chip1">move</a><br /></div>
    <div><input type="hidden" id="chip2"   value="1" >Chip2&nbsp;<a href="#" value="chip2">move</a><br /></div>
    <div><input type="hidden" id="chip3"   value="1" >Chip3&nbsp;<a href="#" value="chip3">move</a><br /></div>
    <div><input type="hidden" id="chip4"   value="1" >Chip4&nbsp;<a href="#" value="chip4">move</a><br /></div>
</div>
Second section :<br />
<div id="second">

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Christopher Kile
Christopher Kile
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of shobhitg
shobhitg

I would like to make sure if I get your question perfectly.

You want to move the clicked "chip" from first div to second.

You code is  doing it. I have already tested that it works.

Am I missing something?
shobhitg,

He wanted it moved to the second div and REmoved from the first div.  I don't know how to word that using the jQuery code, but I believe my solution fits.  Perhaps you know how to clear the HTML from the first div, using jQuery?
Even if I delete  the "remove" line.

The reason is "appendTo" second Div does the job of removing it from the first Div as well.

Explained here: http://api.jquery.com/appendTo/

Hence this would be more optimized code.
 <script type="text/javascript">                                         
   // we will add our javascript code here   
	$(document).ready(function() {
		$("a").click(function() {
			$(this).parent().appendTo("#second");
			$("<input/>").attr({
				id: $(this).attr("value"),
				style: "border:none;font-weight:bold;background-color:white;",
				value : "I'm "+$(this).attr("value")
			}).appendTo("#second");
		});
	});
</script>

Open in new window

* I sent my prev msg too early without checking. My first line was supposed to be:

It works, even if I delete  the "remove" line.
Avatar of brad0525

ASKER

This solution is correct...