0

I have two input fields, both of them have onchange event listener added to them:

HTML

<input type="number" size=5 style="width:80px;" id="funit" autocomplete="off"  required>
<input type="number" size=5 style="width:80px;" id="tunit" autocomplete="off"  required>

JAVASCRIPT

document.getElementById("funit").addEventListener("change",f1);
document.getElementById("tunit").addEventListener("change",f1);

function f1(){
    var funit=document.getElementById("funit").value;
    var tunit=document.getElementById("tunit").value;

    if(funit.toString()!="" && tunit.toString()!=""){
        if(funit>tunit){
            alert("incorrect units");
            document.getElementById("funit").value="";
            document.getElementById("tunit").value="";
        }
    }
}

Now I have another function which fetches the values from a row of a table and inserts them into the fields. Like for example:

 funit=6;
 tunit=7;

Now if I add a 0 along with the input in funit, i.e., if I make it 60, then it should trigger the onchange listener, but it doesn't. Only when I erase both the input fields, and then type again, does the event listener get triggered. Why so? How do I fix this?

  • 1
    `value` will always be a string. Did you mean to coerce the string to a number instead: `Number(value)`? That would make sense of `if (funit > tunit)`. – Andy Aug 27 '21 at 07:22
  • https://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually may be related – capchuck Aug 27 '21 at 07:22
  • the input type is number, how can the value be string. Please explain –  Aug 27 '21 at 07:23
  • The input _type_ is a number but the _value_ you get from it will always be `typeof` string. You can check it out for yourself. – Andy Aug 27 '21 at 07:31
  • You should probably provide a runnable sample, it would help a lot to debug it. – sjahan Aug 27 '21 at 07:35

1 Answers1

0

 document.getElementById("funit").addEventListener("change",f1);
    document.getElementById("tunit").addEventListener("change",f1);

    function f1(){
        var funit=document.getElementById("funit")
        var tunit=document.getElementById("tunit")
        

        if(funit.value && tunit.value){
            if(Number(funit.value)>Number(tunit.value)){
                alert("incorrect units");
                funit.value="";
                tunit.value="";
            }
        }
    }
<input type="number" size=5 style="width:80px;" id="funit" autocomplete="off"  required>
<input type="number" size=5 style="width:80px;" id="tunit" autocomplete="off"  required>
Ishan Bassi
  • 490
  • 1
  • 5
  • 13