Reputation: 31
I am trying to make a function that will ask a user to pick two integers and spit out the smallest one in the form of alerts after the button is clicked. I am not sure what I am doing wrong because whatever i write in the function is coming out as an alert and not the actual event I am trying to achieve.
function smallestNumber() {
var smallNumber= Math.min(prompt('pick a number').value , prompt('pick another number').value);
console.log(smallNumber);
}
alert(smallestNumber);
document.getElementsByTagName("button").addEventListener("click", smallestNumber);
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>testing script</title>
</head>
<body>
<button>this button</button>
<script src="testscript.js"></script>
</body>
</html>
JSfiddle link: https://jsfiddle.net/ypvL9oyd/
Upvotes: 0
Views: 46
Reputation: 1644
document.getElementsByTagName()
returns an array.
prompt()
returns the answer directly; it's not in prompt().value
, which is undefined
prompt
returns a string, so you need to remember to parse it into an integer to use it in Math.min()
function smallestNumber(){
var smallNumber= Math.min(parseInt(prompt('pick a number')) , parseInt(prompt('pick another number')));
console.log(smallNumber);
alert(smallNumber);
}
document.getElementsByTagName("button")[0].addEventListener("click", smallestNumber);
Upvotes: 0
Reputation: 104795
It's because you named your function smallestNumber
and your variable smallNumber
- but you alert smallestNumber
(the name of your function) - alert
the correct variable!
alert(smallNumber)
And as pointed out by @AtheistP3ace - your alert
is outside your function.
function smallestNumber(){
var smallNumber = Math.min(prompt('pick a number').value , prompt('pick another number').value);
alert(smallNumber);
}
Upvotes: 2