-4
<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

2 Answers2

1

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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • _“converts them to ints”_ — No, it coerces the strings to numbers. Consider using [`Number`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#Function_syntax) or [`parseFloat`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) instead, or, specifically for ``s, [`.valueAsNumber`](//developer.mozilla.org/docs/Web/API/HTMLInputElement#Properties). – Sebastian Simon Nov 29 '21 at 17:48
  • I was trying to simplify my explanation when I said "converts them to ints." Also, I use multiple languages so I sometimes forget what each ones calls primitive "number" values. – gen_Eric Nov 29 '21 at 17:51
  • @SebastianSimon What's wrong with using the [unary `+`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus) operator? Why would I use `parseFloat` over `parseInt` on what I would assume is an "integer" input? Also, I didn't know about `valueAsNumber`. – gen_Eric Nov 29 '21 at 17:52
  • 1
    There’s nothing wrong with unary `+`, but it can make code less readable. All I want is to encourage _considering_ the other options because they may be more readable or make more sense, but it comes down to preference in the end. I wouldn’t assume `` to be integer inputs. – Sebastian Simon Nov 29 '21 at 17:56
1

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.

Math.min() - MDN

valueAsNumber attribute - MDN

jbritain
  • 94
  • 4