Welcome to WebmasterWorld Guest from 54.147.44.93

Forum Moderators: open

Message Too Old, No Replies

multiple use of 'html()' in jQuery

works first time, but not subsequent

     

sssweb

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

5+ Year Member



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

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

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



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

sssweb

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

5+ Year Member



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

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

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



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

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

5+ Year Member



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

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

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Glad to help. :)
 

Featured Threads

Hot Threads This Week

Hot Threads This Month