0

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>
2
  • 6
    what is wrong with current ? Commented Jun 7, 2017 at 9:46
  • i would start by confirming that the jquery is executed after the page is fully loaded, and html fully constructed, having your jquery in the $(function() { }); Commented Jun 7, 2017 at 9:48

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.