Brian Norcia
Brian Norcia

Reputation: 11

String and number concatenation

I have this little script that adds a a certain increment to numbers from text field.
I have two text fields, Text1 and Text2.
Text1 takes the input numbers,the function adds a plus 6, i.e. makes a 4 a 10. No issues with getting the input from Text1 element.
I would like to change the addOn = 6 to any number I choose via Text2 input.
I have tried
let addOn = document.getElementById("Text2").value"
with no luck.

Not sure what I am doing wrong here. Some help would be much appreciated.

let input = document.getElementById("Text1").value
let addOn = 6
let splitToArr = input.split(' ')
let doMathOnArr = splitToArr.map((i) => {
    return parseFloat(i) + addOn
})
let result = doMathOnArr.join(' ')
document.write(result);

Upvotes: 0

Views: 86

Answers (2)

symlink
symlink

Reputation: 12208

I'm not sure what you were doing by splitting input, but you can grab the second input the same way you grabbed the first.

Update

I assume you want to separate values by spaces in Input1 and add the Input2 number to all of them. See my edit.

let inp1 = document.getElementById("Text1")
let inp2 = document.getElementById("Text2")

document.querySelectorAll(".txt").forEach(el => {
    el.onkeyup = () => {
        let input = inp1.value
        let addOn = inp2.value
        let result = input.split(" ").map(num => {
            return parseFloat(num) + parseFloat(addOn) 
        }).filter(el => !isNaN(el)).join(" ")
        if(result){
            console.log(result)
        }
    }
})
<input id="Text1" class="txt" />
<input id="Text2" class="txt" />

Upvotes: 1

jeprubio
jeprubio

Reputation: 18032

I would try executing parseInt or parseFloat to the Text2 value, otherwise it will add a string as it's what the Text2 value is and the result might not be what you expect:

let addOn = parseFloat(document.getElementById("Text2").value);

Or do the parseFloat later on, inside the arrow function:

let doMathOnArr = splitToArr.map((i)=>{ 
   return parseFloat(i) + parseFloat(addOn)
})

Upvotes: 1

Related Questions