Jack Casas
Jack Casas

Reputation: 994

Changing href value from JavaScript

I have this example in JsFiddle.

http://jsfiddle.net/PtNfD/114/

<a href="http://www.yahoo.com" target="_blank" id="changeMe">Yahoo</a>
<a href="http://www.yahoo.com" target="_blank" id="changeMe">Not working</a>

$(document).ready (function () {


    $('#changeMe'). click (function (e) {
        var goLucky = Math.floor(Math.random()*12);
        if (goLucky % 2 == 0) {
            this.href = "http://www.google.com";
        } else {
            this.href = "http://www.hotmail.com";
        }
    });
});

The href change works in the first link, but not in the second. How can I make it work for both links??

The number of links in my page is dynamic, because I create the links with PHP, so I need the href change to work in all generated links.

Upvotes: 3

Views: 130

Answers (3)

jojo
jojo

Reputation: 1145

IDs should be used once per webpage. Classes can be used more plentifully. Remember your specificity. Use class instead of id: http://jsfiddle.net/PtNfD/115/

<a href="http://www.yahoo.com" target="_blank" class="changeMe">Yahoo</a>
<a href="http://www.yahoo.com" target="_blank" class="changeMe">Not working</a>

$(document).ready (function () {


    $('.changeMe'). click (function (e) {
        var goLucky = Math.floor(Math.random()*12);
        if (goLucky % 2 == 0) {
            this.href = "http://www.google.com";
        } else {
            this.href = "http://www.hotmail.com";
        }
    });
});

Upvotes: 0

Brian Leishman
Brian Leishman

Reputation: 8575

You cannot use an ID on two different elements in HTML. You need to asign each of those a different ID or the same class instead and then apply your href change on each of the IDs, or the class

Upvotes: 1

War10ck
War10ck

Reputation: 12508

id attributes must be unique. You should convert the value changeMe to a classname for use on multiple elements. Then your existing code should work:

<a href="http://www.yahoo.com" target="_blank" class="changeMe">Yahoo</a>
<a href="http://www.yahoo.com" target="_blank" class="changeMe">Not working</a>

$(document).ready (function () {


    $('.changeMe'). click (function (e) {
        var goLucky = Math.floor(Math.random()*12);
        if (goLucky % 2 == 0) {
            this.href = "http://www.google.com";
        } else {
            this.href = "http://www.hotmail.com";
        }
    });
});

Optionally, you could add a unique id to the second anchor tag and modify the JavaScript code accordingly.

Upvotes: 8

Related Questions