shevatvb
shevatvb

Reputation: 31

How to specify different action onclick for dynamic buttons with the same id

I have three buttons with the same ID. They're added dynamically to the page.

<div class="row" id=rigacite">
<p id="corpo">
  some text some text
  some text some textsome text some textsome text some textsome text some textsome text some textsome text some textsome text some textsome text some textsome text some textsome text some text
  <button id="show"> </button>
  </p>
<p id="corpo">
  other text other text other text other textother text other textother text other textother text other textother text other textother text other textother text other textother text other textother text other textother text other textother text other textother text other text
  <button id="show"> </button>
  </p>
<p id="corpo">
another text another textanother textanother textanother textanother textanother textanother textanother textanother textanother textanother text
  <button id="show"> </button>
  </p>
</div>

When I click on one of them i want it to show the content of its parent

. Each parent

has a different text. How can I do that? I write this code,

var $t = jQuery.noConflict();
$t(document).ready(function() {
	
	    $t('#rigacite #corpo').each(function()
	    {
		    var maxLength = 90;
			var myStr = $t(this).text();
			
			if(myStr.trim().length>maxLength)
			{
				var newString, removedStr;

				newString = myStr.substring(0, maxLength);
				removedStr = myStr.substring(maxLength, myStr.trim().length);
				
				$t(this).empty().html(newString);
				
				$t(this).append('<br/><br/><button id="show" class=" btn fa fa-plus-circle"></button>');
				
				
				
				$t(document).on("click", "#show", function()
				{
					
					$t(this.parentNode).html(newString+removedStr);
					
					
				});
					
				
			}
		});
});

It works when I click on the first one, but when I click on the others the same text of the first parent is shown. Can somebody help me? Thank you in advance.

Upvotes: 1

Views: 59

Answers (1)

ANVerona
ANVerona

Reputation: 459

Once you've fixed the id issue in your HTML to use class instead of id (see the fiddle), you can use something like this:

$('.show').on('click', function(){
    alert($(this).parent().text());
});

Here's a fiddle.

You can place this handle directly in your ready function, instead of putting it inside the each() function.

EDIT: also the whole string manipulation you do inside the each function, can be done in the click handle. Simply get the string of the button's parent; basically replace this

var myStr = $t(this).text();  // here 'this' is the paragraph

with

var myStr = $t(this).parent().text();   // here 'this' is the button

Upvotes: 1

Related Questions