Meter to yard without clicking the submit button

<?php
if ( isset ($_POST['meter']) )
{ 
$meter=$_POST['meter'];
$yard=$meter*0.9144;
}
else
{ 
$meter=10000;
$yard=9144;
}
?>

<form method="post">
<input type="text" name="meter" value="<?php echo $meter ?>"> meter<br>
<input type="text" name="yard" value="<?php echo $yard ?>"> yard
<input type="submit">
</form>

I have the code above,
If I enter “meterNumber” in the input box “meter” and click the submit button,
“yardNumber” will be seen the input box “yard”.

I like to make it like the following.
If I enter “meterNumber” in the input box “meter”,
“yardNumber” will be simultaneously seen the input box “yard” without clicking the submit button.

Give the form a unique identifier so that the script can easily find it, and put the script at the bottom just before the </body> tag.


<body>
<form id="convert">
    ...
</form>

<script type="text/javascript" src="script.js"></script>
...
</script>
</body>

Your PHP script uses a default value for the form values when the page starts, so lets do that in the form itself.
We don’t put in a value for the yard, so that we can use our conversion script instead. That allows us to later on easily change the starting value in the meter field.


<input type="text" name="meter" value="10000"> meter<br>
<input type="text" name="yard"> yard

We will update the form when the page first starts.

Gain a reference to the form, so we can use its elements collection to access parts of the form, and attach a function to the onkeyup event of the form element called meter.


var form = document.getElementById('convert');
var meter = form.elements.meter;

That lets us attach a function to the onkeyup event of the meter field. We can also trigger that event from the script so the conversion also occurs when the page loads.


meter.onkeyup = convertMetersToYards;
meter.onkeyup();

In the convertMetersToYards function, convert the fields string value to a number. If it’s not a valid number, use 0 instead.


function convertMetersToYards() {
    var meters = Number(this.value) || 0;
    ...
};

Lastly, update the yard field with a converted value.


function convertMetersToYards() {
    ...
    this.form.elements.yard.value = meters * 0.9144;
}

The resulting code that you end up with is:


<form id="convert">
    <input type="text" name="meter" value="10000"> meter<br>
    <input type="text" name="yard"> yard
</form>

<script type="text/javascript" src="script.js"></script>

script.js


function convertMetersToYards() {
    var meters = Number(this.value) || 0;
    this.form.elements.yard.value = meters * 0.9144;
}

var form = document.getElementById('convert');
var meter = form.elements.convertMetersToYards;
meter.onkeyup = convertMetersToYards;
meter.onkeyup();

</script>