Kenny Nguyen Kenny Nguyen - 1 year ago 88
Javascript Question

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) {
var _self = $(this);
userId ='id');
var newLink = '/users/view/' + userId //I'd like to eventually use this as new href link

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

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


Any suggestion would help. I'm using jQuery 3.2.1

Answer Source

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) {


        var _self = $(this);
        userId ='id');

        var newLink = '/users/view/' + userId
        $(".view_me").prop("href", "");



Working JSFiddle:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download