Question

I have done a hide and show of a div element, on clicking a

element with class toggleIt by using the toggle() function. But how to change the name of the p tag after clicking it?

For eg, I have the name as 'Hide' for the p tag. On clicking this I hide a div. Now, I also want the name to change to 'Show'. How do I do that?

<p class="toggleIt">Hide</p> //want this to change to 'Show' after clicking

$('.toggleIt').click(function(){

     $('#common_fields').toggle();

});
Was it helpful?

Solution

I think you intend to change the text of the P element as opposed to its name.

<p class="toggleIt">Hide</p> //want this to change to 'Show' after clicking
$('.toggleIt').click(function(){
  $('#common_fields').toggle();
  var thisElem = $(this);
  thisElem.text(thisElem.text() === "Show" ? "Hide" : "Show");
});

OTHER TIPS

You need to know if the #common_fields element is visible or not, in order to get the right 'Show' or 'Hide' text value:

$('.toggleIt').click(function(){
  var $commonFields = $('#common_fields');
      text = $commonFields.is(':visible') ? 'Show' : 'Hide';

  $(this).text(text);
  $commonFields.toggle();
});

Try the above snippet here.

$(".toggleIt").text("Show");

Make sure that that's the only <p> tag with the "toggleIt" class or you'll need to use a different selector.

According to the code you posted above, you're not trying to change the name attribute, you're trying to change the text value/innerHTML of the element.

That's done by calling:

$('.toggleIt').click(function(){
     $('#common_fields').toggle().text('Show');
});

If you actually wanted to change the name attribute of the p element, you'd do:

$('.toggleIt').click(function(){
     $('#common_fields').toggle().attr('name', 'Show');
});
var toggleString = {
    show:'Show',
    hide:'Hide'
};

$('.toggleIt').toggle(function() {
    $('#common_fields').hide();
    $(this).text( toggleString.show );
}), function() {
    $('#common_fields').show();
    $(this).text( toggleString.hide );
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top