cup_of cup_of - 5 months ago 24
HTML Question

how put put dynamically populated number into input value field

hello i have dynamically populated value coming from an external js file. the value is working just fine when i call it in the html page but im stuck on how to have an input field display this value.

here is my html:

<form action="../mail.php" method="POST" class="location-form">

<div class="device-details">
<h2>Device: iPhone5</h2>
<h2>Repair Cost: <span id="result">0</span></h2>
</div>

<input name="device" type="hidden" id="device" value="iPhone5" maxlength="20">
<input name="cost" type="hidden" id="cost" value="" maxlength="20">

<div class="submit-btn">
<input type="submit" value="Submit Request" />
</div>

</form>

<script>
document.getElementById("result").innerHTML = localStorage.getItem("sum");
</script>


at the top, in the div "device-details", the h2 "repair cost" is populating the value just fine, no issues. but i cannot seem to populate the last input with this value.

<input name="cost" type="hidden" id="cost" value="(need the value here)" maxlength="20">


i need the value of the input field to mimic the value of the repair cost at the top in order to send that value to an email address.

ive tried inserting the following into the value and it didnt work

value="<span id='result'>0</span>"


ive tried creating a variable in php and then putting the variable into the value field, and it did not work

<?php
$my_var = '<span id="result">0</span>';
?>

value="<?php echo '$my_var'); ?>"


ive also tried:

value="<?php echo htmlspecialchars($my_var); ?>"


these last two just returned the actual html code

<span id="result"></span>


instead of the populated value

hopefully one of you guys can help me out :) thanks!

Answer

Try this one.

<!DOCTYPE html>
<html>
<body onload="abc()">
<form action="../mail.php" method="POST" class="location-form">

            <div class="device-details">
              <h2>Device: iPhone5</h2>
              <h2>Repair Cost: <span id="result">0</span></h2>
            </div>

            <input name="device" type="hidden" id="device" value="iPhone5" maxlength="20">
            <input name="cost" type="hidden" id="cost" value="" maxlength="20">

            <div class="submit-btn">
                <input type="submit"  value="Submit Request" />
            </div>

      </form>

      <script>

        function abc(){
        document.getElementById("result").innerHTML=localStorage.getItem("sum");
        document.getElementById("cost").value = localStorage.getItem("sum");
        }
      </script>

    </body>
</html>