JsusSalv
JsusSalv

Reputation: 517

Text change on click for toggling elements

I'm trying to change a '+' into '-' when toggling elements. I've tried a few things but once the symbol changes it won't toggle back and forth like it should. I've searched the other posts but they don't work for my bit of code.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
//Hide (Collapse) the toggle containers on load
$("trace_dump").hide();

//Slide up and down on hover
$("h3").click(function(){
    $(this).next("trace_dump").slideToggle("slow");
    $(this).text($('span').text() == '+' ? '-' : '+');
});
});
</script>

...and here's the html:

<h3><span>+</span>print_r()</h3>
<trace_dump>
    print_r($e);
</trace_dump>
<h3><span>+</span>var_dump()</h3>
<trace_dump>
    var_dump($e);
</trace_dump>

Can I get some ideas?

Upvotes: 0

Views: 458

Answers (5)

krishna
krishna

Reputation: 1351

This will work as well. If you give the context as the second parameter, then the search is limited to within the enclosing element. In this case its "h3"

 var element = $('span',$(this));
    element.text(element.text() == '+' ? '-':'+');

Upvotes: 0

Adeel
Adeel

Reputation: 19228

you need to enclose it in a div that supports show/hide operations. there is no html tag trace_dump This works. See demo here

UPDATE:

jQuery(document).ready(function() {             
$("trace_dump").hide();
//Slide up and down on hover
$("h3").click(function(){
    $(this).next("trace_dump").slideToggle("slow");
    $(this).find("span").html(($(this).find("span").text().trim() == '+' ? '-' : '+'));  
}); 

});

Upvotes: 0

Puneet
Puneet

Reputation: 1014

I think, after the first call to your function, the span element is replaced by + or - And so from the next call onwards, jquery does not find the span element at all

I haven't tested it, but reading the code makes me believe this.

Maybe remove the span entirely and replace by + or -

Hope it helps

Upvotes: 0

jAndy
jAndy

Reputation: 235962

In your inline conditional check, you query for all <span> elements and compare the .text() contents. This obviously won't work. Use $(this).find('span') or even better, do it like this:

$(this).find('span').text(function(i, text) {
    return text === '+' ? '-' : '+';
});

Demo: http://jsfiddle.net/qR2NU/8/

Upvotes: 1

Gareth
Gareth

Reputation: 5719

In this line:

    $(this).text($('span').text() == '+' ? '-' : '+');

this is refering to the h3 and not the span like I think you intended.

Try this:

$(this).find('span').text($(this).find('span').text()=='+'?'-':'+');

Upvotes: 1

Related Questions