0

I am a beginner at JavaScript and am currently trying to create a very basic webbsite for throwing dice. For some reason I can't add two numbers together correctly. The following code is supposed to add the value of each dice, but doesn't. Could someone please explain why, and how to fix it?

        let numRolls = document.getElementById('numhitrolls').value;
        let modifier = document.getElementById('tohit-modifier').value;
        

        if(document.getElementById('neither').checked == true){
            for( let i = 0; i < numRolls; i++){
                roll = (Math.floor(Math.random() * 20) + 1);
                roll += modifier;
                alert(roll);
                }

For some reason I get a message with a number that is way to high. I want to add the value of the modifier and the roll, but instead I'm getting a value such as '1112' (modifier = 12), and I can't understand why. Help is much appreciated

Thegreen
  • 23
  • 3
  • 5
    `Element.value` will always return a **string**. It's your job as a developer to convert `value` to the needed, float, integer, number etc. Open console and type `11 + "12"` what to you see? Exactly, `"1112"` instead of `23`. Therefore, use `roll += +modifier;` or `roll += Number(modifier);` – Roko C. Buljan Jul 02 '23 at 22:47
  • give me full code html ans js – XMehdi01 Jul 02 '23 at 22:49
  • 1
    FYI if the inputs are `type="number"` you can use [valueAsNumber](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#valueasnumber) – Phil Jul 02 '23 at 22:51
  • @Philisonstrike Hey that's handy! Thanks. – Brad Jul 03 '23 at 01:29

0 Answers0