0

I tried to make a function that receive data from user and combine such data either by concatenation in case of string or by getting the sum as a result if the entered data was integer. My main problem is that I don't know what what condition in if statement I use to JavaScript act according to data entered by user.

That's my last invented code to solve such problem

function GetFullName() {
            var first = document.getElementById('FirstName').value;
            var last = document.getElementById('LastName').value;

            if (first == "string" || last == "string") {               
                document.getElementById('FullName').value = first + " " + last;

            } else {
                var first = parseInt(document.getElementById('FirstName').value);
                var last = parseInt(document.getElementById('LastName').value);

                document.getElementById('FullName').value = first + last;
               
            }
            document.getElementById('FirstName').focus();
        }
<form>
        First Name <input type="text" id="FirstName" />
        Last Name <input type="text" id="LastName" />
        <input type="button" value="submit" onclick="GetFullName()" />
        <input type="reset" value="reset" />
        <br />
        Full Name <input type="text" id="FullName" />
    </form>

1
  • var first; try { first = JSON.parse(document.getElementById('FirstName').value); } catch (e) { first = document.getElementById('FirstName').value } Commented Jun 13, 2020 at 20:09

1 Answer 1

2

when you get an element's value it will always be a string,

you can check of a variables type by typeof first

for your specific problem if you want to check if the user inputted integers then you will have to use isNaN

if(isNaN("123")) {

} else {
   //this executes
}

All in all the new code would be:

if (isNaN(first) || isNaN(last)) {
    document.getElementById('FullName').value = first + " " + last;
} else {
    document.getElementById('FullName').value = parseInt(first) + parseInt(last);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.