Home > Software engineering >  How can I add an value to an input type
How can I add an value to an input type

Time:03-22

How can I add an value to an input type.

I'm currently working on a converter for meter to kilometer, to mile, ...

I've created different input types in my HTML Code and took the value of them in JS, which worked completely fine, and I prevented the page from reloading after I click submit. Now I want to reassign the new, calculated value (kilometer.value = meter / 1000), but this doesn't work.

It works completely fine, when I'm putting an console.log after the variable meter and the first variable kilometer. It logs the correct number - the reassignment just doesn't work.

JavaScript:

const calculateMeter = () => {
    let meter = document.getElementById("meter").value;

    let kilometer = document.getElementById("kilometer").value;
    kilometer.value = meter / 1000;
}

HTML:

<form id="calculator" onsubmit="calculateMeter(); return false">
    <label for="kilometer">Kilometer:</label>
    <input type="number" id="kilometer"><br>

    <label for="meter">Meter:</label>
    <input type="number" id="meter"><br>

CodePudding user response:

You should convert meter to intiger

const calculateMeter = () => {
    let meter = document.getElementById("meter").value;

    let kilometer = document.getElementById("kilometer").value;
    kilometer.value = Number(meter) / 1000;
}

CodePudding user response:

Did you mean something like, that?

let meterInp = document.getElementById("meter");
let kilometerInp = document.getElementById("kilometer");

meterInp.addEventListener("change", ()=>{
  kilometerInp.value = ( meterInp.value)/1000;
});
kilometerInp.addEventListener("change", ()=>{
  meterInp.value = ( kilometerInp.value)*1000;
});
<form id="calculator" onsubmit="calculateMeter(); return false">
    <label for="kilometer">Kilometer:</label>
    <input type="number" id="kilometer" step="0.00001"><br>

    <label for="meter">Meter:</label>
    <input type="number" step="0.01" id="meter"><br>
</form>

The ( ) converts string to number. for e.g. ( meterInp.value)/1000

  • Related