Search code examples
javascriptjqueryhrefejs

Cannot change href value of a tag


Im trying to change my href value, but it doesn't seem to be changing at all. I've tried both jQuery and javascript method and neither work.

<a type="button" class="view_me btn btn-primary" href="#">View Full</a>
$(document).on("click", ".click_row", function (e) {
  e.preventDefault();
  var _self = $(this);
  userId = _self.data('id');
  var newLink = '/users/view/' + userId //I'd like to eventually use this as new href link

  $(".view_me").prop("href", "www.google.com"); // Tried testing with a simple webpage

  // document.getElementById('view_test').href = "www.google.com"; // Tried this as well, doesn't work

  console.log(newLink)
});

Any suggestion would help. I'm using jQuery 3.2.1


Solution

  • There were a few issues that were impeding the intended behavior. First, your click function wasn't being called because it was looking for the click_row class; I believe you may have meant for this to be the view_me class instead. Second, you need to add https:// to the beginning of the URL to have it redirect properly. Lastly, you needed to set the href property of the link in your code that had the class view_me, not the id view_me.

    EDIT: Also, delete e.preventDefault() or else you can only open the link in a new tab.

    The following JS code fixes these issues and produces the desired behavior:

        $(document).on("click", ".view_me", function (e) {
    
            //e.preventDefault();
    
            var _self = $(this);
            userId = _self.data('id');
    
            var newLink = '/users/view/' + userId
            $(".view_me").prop("href", "https://www.google.com");
    
            console.log(newLink);
    
       });
    

    Working JSFiddle: https://jsfiddle.net/2m0297j1/