Jquery toggle text changes only once

I have the following code that should change the value of h2 from "Show more" to "Show less", and then back when the parent element is clicked.

The if () test checks OK and changes the text to "Show less", but it will not change it anymore and always displays a "Show more" warning, so it just does not detect the else () condition.

I searched high and low to find out why, but haven't found a solution yet.

I know this is a question with noob, so apologize for this, but I tried to find a solution before posting here.

Thank.

$('#panels > .feature').click(function() {
    if($(this).children('h2').val('Show More')) {
        $(this).children('h2').text('Show Less');
        alert('Show More was found');     
    }
    else {
        $(this).children('h2').text('Show More');
        alert('Show Less was found');
    }   
      $(this).next(".info_box").animate(
     {'height':'toggle'}, 'slow', 'linear'
     );    
});

This HTML address:

<div id="panels">
 <div id="Email" class="feature">
    <h1>LiveContent</h1><h2>Show More</h2>
 </div>
<div class="info_box">Information will go in this div which should slide in and out.</div>
<div id="Email" class="feature">
  <h1>Publishing Solutions</h1><h2>Show More</h2>
 </div>
<div class="info_box">Information will go in this div which should slide in and out.</div> 
<div id="Email" class="feature">
  <h1>Title 1</h1><h2>Show More</h2>
 </div>
<div class="info_box">Information will go in this div which should slide in and out.</div>
</div>
+3
source share
4 answers

.val(), , .text() ( , ), :

if($(this).children('h2').text() == 'Show More')) { //here
    $(this).children('h2').text('Show Less');
    alert('Show More was found');     
}
else {
    $(this).children('h2').text('Show More');
    alert('Show Less was found');
}

, , .text() .slideToggle(), :

$('#panels > .feature').click(function() {
    $(this).children('h2').text(function(i, t) {
      return t == 'Show More' ? 'Show Less' : 'Show More';
    });
    $(this).next(".info_box").slideToggle("slow");
});

.

+2
if($(this).children('h2').val('Show More')) {

.text .val?

+3

.val('Show More) HTML value 'Show More'. , getter, - , . , .

, .val('Show More') - .text() == 'Show More'.

+1

. text , :

if($(this).children('h2').text() == 'Show More')

The code did not work correctly even the first time, since it always did the same. The reason he seemed to be triggered for the first time was that he always did what he had to do for the first time.

+1
source

Source: https://habr.com/ru/post/1777458/


All Articles