Home » Php » javascript – Change links name and href after it's been clicked

javascript – Change links name and href after it's been clicked

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have the following link:

<span class="hds-icon-star-empty" aria-hidden="true"><!-- --></span>  <a href="<?=$this->recordLink()->getActionUrl($this->driver, 'Save')?>" data-lightbox class="save-record" data-id="<?=$this->escapeHtmlAttr($this->driver->getUniqueId()) ?>"><?=$this->transEsc('Add to favorites')?></a><br/>
        <br/>

Now I want to change the text “add to favorites” to “allready added to favorites” after the link has been clicked.
I guess a onclick-function would not work as it would redirect, to the new page before the link would be clicked.

How to&Answers:

You can stop default behaviour of link using event.preventDefault()

But also you have to send request to target page using AJAX for performing actual functions that are related to database.

document.querySelector("a").onclick = function(){
  event.preventDefault();
  this.innerHTML = "Already Added to Favorites";
  var href = this.getAttribute("href");
  //$.ajax({url : href ,...});
};
<a href = "/">Add to favorites</a>