简体   繁体   中英

Passing a variable from an external javascript file onto a value in html?

I'm making a "shopping form" where I can edit prices in an external .js file by changing a single variable from the .js, and will be reflected in a value within my html that totals up the total cost.

The Javascript file, called "prices.js"

var x = "100.00";
var y = "200.00";

My html:

<input type="hidden" name="item_name_1" value="Banana for Sale">
<input class="amount" type="hidden" name="amount_1" value=x>

<input type="hidden" name="item_name_2" value="Orange for Sale">
<input class="amount" type="hidden" name="amount_2" value=y>

Essentially, I'm trying to pass the "x" and "y" variable from my external javascript onto the "values" in my html for each item. I'm a complete noob at this, so the above obviously isn't working.

Just to clarify, I don't need the code to write the value immediately, only to change the value so that it can be written by another function (which is already taken care of) that totals up all of the amounts from all items above.

Thank you all for your help!

You can use getElementsByName to find your hidden variable and then you can populate it with the value of x . The JavaScript below needs to be saved to your prices.js file. Just to clarify, getElementsByName is returning an array, so I am taking the first entry to be able to set the value field.

 x = 10 y = 5 document.getElementsByName("amount_1")[0].value = x document.getElementsByName("amount_2")[0].value = y document.write(document.getElementsByName("amount_1")[0].value + '<br>') document.write(document.getElementsByName("amount_2")[0].value + '<br>') 
 <input class="amount" type="hidden" name="amount_1" value=""> <input class="amount" type="hidden" name="amount_2" value=""> 

Try to assign variables to the inputs using .val() and class selector, eg :

<script>
    $(function(){
        $('.amount_1').val(x);
        $('.amount_2').val(y);
    })
</script>

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM