<body>
<div class="container">
<input type="number" id="first">
<input type="number" id="second">
<button id="butId">Максимум</button>
<p id="out">
123
</p>
</div>
<script>
function min(a, b) {
console.log('1');
if (a>b) return b
else return a;
}
butId.addEventListener('click', function(e){
out.innerHTML=min(first,second);
})
</script>
</body>
it supposed to show in <p id='out'>
the minimal number of the two typed in. it shows
[object HTMLInputElement]
instead of a number and i do not see any errors
CodePudding user response:
You need to get the actual value entered into each <input>
element, not the element itself.
butId.addEventListener('click', function(e) {
out.innerHTML = min( first.value, second.value);
});
Note: The
before the variables converts them to ints.
CodePudding user response:
You are attempting to find the minimum value of each element, as opposed to the number inside it. You instead want to use
out.textContent = Math.min(first.valueAsNumber,second.valueAsNumber)
Here, we are getting the valueAsNumber
of each input box and performing our min()
calculation on it. This takes the text inside the input
box and converts it to a number. You may also notice the Math.min
, JS has a min
function built in, so you do not need to define your own function for it. Additionally, it's good practice to use textContent
to prevent XSS injection.