homepage Welcome to WebmasterWorld Guest from 23.22.173.58
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
multiple use of 'html()' in jQuery
works first time, but not subsequent
sssweb




msg:4448056
 4:36 pm on May 1, 2012 (gmt 0)

I'm using jquery to change the html content of a div when certain buttons are clicked. The code works fine on the first change. But if I then click a different button to change it to something else, I get a blank div (no text). I know all buttons work because when I try each of them first, they change the content correctly.

Do I have to re-set something after each change to get the next one to work?

Here's sample code I'm using:

$( "#button1" ).click(function() {
var htmlStr = $( "#text2" ).html();
$("#change-div").html(htmlStr);
});

 

Fotiman




msg:4448068
 5:32 pm on May 1, 2012 (gmt 0)

Works for me. Here's a jsfiddle that demonstrates it:
[jsfiddle.net...]

sssweb




msg:4448078
 5:53 pm on May 1, 2012 (gmt 0)

Thanks Fotiman - I had all text variations in different <p> tags w/in <div> change-div. Not sure why that's a problem, but it works when I use separate divs like you did.

Fotiman




msg:4448083
 6:09 pm on May 1, 2012 (gmt 0)

Not sure I understand what you mean. Did you have something like this?

<div id-"change-div">
<div id="text2">2...</div>
<div id="text3">3...</div>
</div>

In other words, is the source of the text that you're copying to change-div nested within change-div to begin with? If so, that would cause a problem because after the first call, the source would no longer exist. In other words, after the first call, your DOM would become:


<div id-"change-div">
2...
</div>


Therefore, subsequent button clicks would result in this:

var htmlStr = ( "#text2" ).html();
// htmlStr = null because #text2 no longer exists in the DOM

sssweb




msg:4448098
 6:47 pm on May 1, 2012 (gmt 0)

Yes, that's exactly what I did (except I used <p id="text2">, etc, w/in <div id="change-div">.

When you explain it as you did, it's obvious why it didn't work. Thanks for that.

You guys are great -- us newbies and webmaster wannabe's really appreciate all the help you give. :)

Fotiman




msg:4448129
 8:29 pm on May 1, 2012 (gmt 0)

Glad to help. :)

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved