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.
source to share
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.
source to share
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";
}
});
});
source to share