Changing href value from JavaScript

I have this example at 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";
        }
    });
});

      

Changing the href works in the first link, but not in the second. How can I get it to work for both links?

The number of links on my page is dynamic because I am creating links from PHP, so I need the href changes to work on all generated links.

+3


source to share


3 answers


id

attributes must be unique. You must convert the value changeMe

to a class name 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 can add a unique one id

to the second anchor tag and modify the JavaScript code accordingly.

+8


source


You cannot use an ID on two different elements in HTML. You need to give each of them a different ID or the same class and then apply the href changes to each of the IDs or class



+1


source


IDs must be used once per web page. Lessons can be used more abundantly. Remember your specifics. 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";
        }
    });
});

      

0


source







All Articles