0

I have this loop where I'm creating a link, but bootstrap modals prevents me to use PHP variables properly from the top loop (Yes a loop in loop). So I decided to use jQuery and get the id from the button when it's clicked, and that is fine, but how do I append this into the link without appending the whole link, because there is another ID variable which I'm using again in this links? Here in $value->getId() I need to append value from jQuery.

foreach ($exploredArtistBands as $band) { echo '<a href="/notification/invite/' . $value->getId() . '/' . $band['band_id'] . '">Join to ' . $band['name'] . '</a><br />'; } 
$('.invite').click(function(){ $(this).attr('button-id') }); 
3
  • What (relevant/MCVE) HTML does that php generate? Commented Jan 11, 2015 at 16:26
  • Can you run the foreach loop inside the .click callback, that way you have the value of the button-id wen you need it Commented Jan 11, 2015 at 16:27
  • pastebin.com/hsgKnJkS Commented Jan 11, 2015 at 16:33

1 Answer 1

1

You can modify the url for your link in the click event. You just have to turn your url into something that's easy to parse. Something like the following;

foreach ($exploredArtistBands as $band) { echo '<a href="/notification/invite/{id}/' . $band['band_id'] . '">Join to ' . $band['name'] . '</a><br />'; } 

So you end up with a link like:

href="/notification/invite/{id}/band_id" 

Now in your click handler, replace {id} with the id from the button.

$('.invite').click(function(){ var id = $(this).attr('button-id'); var url = $(this).attr("href"); $(this).attr("href", url.replace('{id}', id)); }); 

The click event will continue to bubble, but with a new url. This will ultimately direct your browser to the right place. This approach smells to me, but it works.

Sign up to request clarification or add additional context in comments.

2 Comments

I think it's a rather nifty solution. jQuery will bind the correct element, so if there's other HTML inside the link, you don't have to worry about the right element. Simple and does the job!
Yes, but when i have more then 1 $('.invite') elements with different ids on each one Jquery replace everywhere the first clicked button, so still need something to be done ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.