Mehrad
Mehrad

Reputation: 11

how to pass variable value to href attribute using javascript or jquery?

I'm trying to use JavaScript random function for pass the different value to href attribute this is my code but it's not the jQuery part is not working:

jQuery:-

var numbers = ["22332233", "44455566", "12322122", "44455566", "12322122", "44455566", "12322122"];
var result = Math.floor(Math.random() * 5);
console.log(result);
console.log(numbers[result]);
$("#phone-tel").attr("href", numbers[result]);

HTML:-

<a id="phone-tel" href="">+353123456789</a>

Upvotes: 0

Views: 3859

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

Your code work fine,if:-

1.jQuery library added before your script code.

2.Wrap your script code inside $(document).ready(function(){..});,if it is on top of your page. If script code is on bottom of the page then wrapping is not necessary.

Working example:-

$(document).ready(function(){
  var numbers = ["22332233", "44455566", "12322122", "44455566", "12322122", "44455566", "12322122"];
  var result = Math.floor(Math.random() * 5);  
  console.log(result);
  $("#phone-tel").attr("href",numbers[result]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="phone-tel" href="">+353123456789</a>

Upvotes: 3

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

jQuery library is missing in your code

By adding jquery library, every thing is working fine with your code. The only issue is, there are only 7 element in the array. So most of th times random number generates the last generated number again and again. To remove this, hold the last value and generate the value other than that.

Upvotes: 0

Related Questions