I need help fixing a JavaScript function using the DOM

Hello coders! Based on one of the projects in the JavaScript curriculum I’m trying to build the Roman Numeral Converted using html and css as well as js.
My problem is that the first time a user inputs a number it works okay but when the user deletes the previous number to insert a new one a message comes. The message that pops up on the screen is one I used in the function just in case the user enters a value outside the ones that they should. But in this case just by deleting that last number the message comes. How can I fix that?

Here is the link of my project in codepen: https://codepen.io/Flor95/pen/abOwLVZ

Thank you so much for your time and have a wonderful Sunday :smile:

Try using <input type=number instead of text inputs, then use the min and max attributes on them. Then you can get rid of the alert.

BTW, love the background pic. :+1:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number

1 Like

Hi! The problem seems to be that the function you’re calling when an input event happens (that’s line 4 in your code) calls the convertToRoman function for whatever the user types in. Therefore, if the user deletes their original response, it’s the same as if they submitted "" (an empty string), which is converted to 0 and thus passes the if condition that makes the alert message pop up.

The easy fix would be to adjust your event function so that it only gets triggered when the input is not equal to an empty string.

However, you might want to go deeper than this, because if you only check whether the input is in the number range, a lot of NaN values will slip by because the condition will end up being false (on account of NaN value not being less than 1 or greater than 4999). For example, your input field allows input such as xyz, 123 456, and so on that can’t be cast to int. You might want to fix this as well :slight_smile:

By the way, @chuckadams had a great idea on how to solve this issue easily, but I’ve tested it and for some reason it still throws an alert when you delete your number. However, doing this will disable non-numerical input, so you might want to use the combination of our ideas.

Experiment with this a little bit and let us know if you’ve managed to solve the issue :smile:

1 Like

Big thanks for your help @chuckadams and @kristina_v ! both of your feedback has been really useful to me. I finally was able to solve this problem.
I solved by changing the original function, more specifically I fixed this:

    if(num<=0 && num!=""|| num>4999){
        alert("Incorrect input. Please insert a number from 1 to 4999")
    }

I added the condition that num!="" which is what happens when you delete the last value in the form :smiley:

1 Like