-8

How can I correct this code using javascript and html. Thanks in advance! please help me out of this problem.

<input type="text" id="text1">
<input type="text" id="text2">
<input type="submit" onclick="submit()">

<script type="text/javascript">
    function submit() {
        var q = document.getElementById('text1');
        var w = document.getElementById('text2');

        if (q > w) {
            console.log('q is greaterthan in w');
        } else{
            console.log('q is less that in w');
        }

    }
</script>   
Kenji Mukai
  • 599
  • 4
  • 8
  • 2
    What are you expecting to have your code do, and what's happening instead? – Chris Forrence Oct 31 '17 at 15:32
  • why do you -rep me :( I dont really know what is the syntax or code here :( – pacificskybeachresort Oct 31 '17 at 15:33
  • What is the problem? What does the console tell you? Are you sure `q` and `w` can be compared using the operator `>`? – msfoster Oct 31 '17 at 15:33
  • 1
    Possibly a duplicate of [this](https://stackoverflow.com/questions/31613748/why-cant-i-call-a-function-named-clear-from-an-onclick-attribute/31613889#31613889), but the question lacks a clear problem statement. – Quentin Oct 31 '17 at 15:33

2 Answers2

-1

You are comparing the DOM elements (input fields) themselves, not their values. In order to get the values and compare those, you have to actually get the .value property and treat them as Numbers (float or integer or whatever it's going to be).

function submit() {
    var q = parseFloat(document.getElementById('text1').value);
    var w = parseFloat(document.getElementById('text2').value);

    if (q > w) {
        console.log('q is greater than w');
    }
    else
    {
        console.log('q is less or equal than w');
    }
}
<input type="text" id="text1">
<input type="text" id="text2">
<input type="submit" onclick="submit()">
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
-2

You have to get the value of the input like this: document.getElementById('text1').value

function submit() {
    var q = document.getElementById('text1').value;
    var w = document.getElementById('text2').value;

    if (q > w) {
        console.log('q is greaterthan in w');
    }
    else
    {
        console.log('q is less that in w');
    }

}
Kenji Mukai
  • 599
  • 4
  • 8
  • Why do I have downvotes if this is a helpful answer? Haha. – Kenji Mukai Oct 31 '17 at 15:51
  • Just your comment now - it happened to my answer as well and just happened again in another question. The answer to why people do this is: Because some people here are idiots. Maybe they have low self-esteem or other problems in their real lifes, who knows. See also: https://meta.stackoverflow.com/questions/255459/is-it-okay-to-downvote-answers-to-bad-questions – Constantin Groß Nov 02 '17 at 18:15