在Laravel中从AJAX更新按钮onClick url

I have a simple form with a "Submit" button and an additional "Add" button in blade template. On form submit there is an ajax callback to a controller which validates provided value. Based on the returned result from the controller, I'd like to change the "Add" button onClick event. Here is blade snip:

<button id="theId" type="button" >Add</button>

Relevant ajax pice:

$.ajax({
        ...
        success: function(result){
           //Update onClick for the add button
           addButton.onclick=function () {
               //location.href = 'www.example.com';
               window.location="www.example.com";
           };
           addButton.html("aNewName");
        }
}

Based on all the sources either location.href or window.location should redirect me to a different page (in my case just a different subpage) but it does not. After hours of research I thought that I get a wrong button or sth is wrong with the ajax itself but then I added addButton.html line and this works well. What do I do wrong here?

Get the button, remove eventually previous click events, add the new event using the http/https prefix, change the text of the button

success: function(result){
   var button = document.querySelector('#theId');
   button.addEventListener('click', function () {
       window.location = 'https://www.google.it';
   });
   button.innerHTML = "my new button text";
}

From the MDN docs here: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers#Registering_on-event_handlers, a handler registered via an on* attribute will be available via the corresponding on* property, but not the other way around.

What this means is that the onclick attribute of the div remains the old event handler in HTML. To keep sanity, always register event listeners with the addEventListener method.

It looks like you are trying to set a jQuery object's onclick property to a function, which is not the right way to set a click event handler in jQuery.

You should use the jQuery object's click method to set a click handler. And use the off method to remove the previous handler:

addButton.off('click');
addButton.click(function () {
  window.location="https://www.example.com";
})

Here's a working fiddle.